Skip to content

Control structures

Sisypheus edited this page Jun 12, 2024 · 3 revisions

How about computing BMI and interpreting the result for people given their weight and height?

That's a good example of introducing control structures in Plume. To do such a thing and especially interpret the BMI result, we need to conditionally check the BMI value and return a message according to the result.

Conditional statements

Conditional statements are a way to execute a block of code only if a condition is met. In Plume, you can use the if statement to conditionally execute a block of code.

// Compute the BMI of a person given their weight and height
fn compute_bmi(weight: float, height: float): str {
  bmi = weight / height * height
  if bmi < 18.5 {
    return "Underweight"
  } else if bmi < 25.0 {
    return "Normal weight"
  } else if bmi < 30.0 {
    return "Overweight"
  } else {
    return "Obese"
  }
}

In the previous example, we have defined a function compute_bmi that takes two arguments weight and height, and returns a string. The function computes the BMI of a person given their weight and height and returns a message according to the result.

Inlined if statement

In some cases, you may want to return a value directly from the if statement. In Plume, you can do this by using the inlined if statement, which is kind of a ternary operator.

// Define a factorial function using an inlined if statement
fn factorial(n: int): int => 
  if n == 0 { return 1 } else { return n * factorial(n - 1) }

In the previous example, the if statement has been used as an expression to return a value directly from the function.

Loops

There are no for or while loops in Plume yet. But you can use recursion to iterate over a list or to perform a specific action multiple times.

// Define a function that iterates over a list
fn iterate_list(l: [int]): int {
  if l == [] {
    return 0
  } else {
    return l[0] + iterate_list(l[1..])
  }
}

In this function, if you try to compile the code, you will get an error because l[0] is not an integer but an optional integer: this is where Plume safety comes into play. You need to handle the case where the list is empty to avoid runtime errors.

Pattern matching

Pattern matching is a way to answer the previous issue. It's a way to match a value against a pattern and to execute a block of code according to the pattern.

// Define a function that iterates over a list using pattern matching
fn iterate_list(l: [int]): int {
  return switch l {
    case [] => 0
    case [x, ..xs] => x + iterate_list(xs)
  }
}

In this function, we have used the switch statement to match the value of l against the patterns [] and [x, ..xs]. The .. operator is used to match the rest of the list.

Thanks to pattern matching, we could have avoided the compile time error we had before and we additionally have a more readable and concise code.

Clone this wiki locally