MoonBit Language Tour MoonBit

If expression

An if expression is a conditional control flow expression that has a result value.

In an if expression, each branch must have the same type. If the condition is true, it returns the result value of the first branch. Otherwise, it returns the result value of the second branch.

The else part is optional. If it is omitted, the type of the whole if expression will be Unit.

Nested if expressions in the else part can be shortened by using else if.

fn fib(x : Int) -> Int {
  if x < 2 {
    x
  } else {
    fib(x - 1) + fib(x - 2)
  }
}

fn main {
  if 5 > 1 {
    println("5 is greater than 1")
  }
  println(fib(5))
  println(weekday(3))
}

fn weekday(x : Int) -> String {
  if x == 1 {
    "Monday"
  } else if x == 2 {
    "Tuesday"
  } else if x == 3 {
    "Wednesday"
  } else if x == 4 {
    "Thursday"
  } else if x == 5 {
    "Friday"
  } else if x == 6 {
    "Saturday"
  } else if x == 7 {
    "Sunday"
  } else {
    "Invalid day"
  }
}