Chapter 2: Making decisions

Guessing game

  • return
  • cond
  • case
  • guards

The same function written three ways. Each is a good fit somewhere.

Early return. reply_if checks a condition and leaves straight away. In Gleam this needs use <- bool.guard(…); in Bea it is just return. The returned value is only computed when the branch is taken.

cond. A list of conditions, and the first true one wins. _ or True is the fallback.

case. Pattern matching on the value itself: 41 | 43 matches either number and g if g > 42 adds a guard.

Open in playground
def reply_if(guess: Int) -> String {
  if guess == 42 {
    return "Correct"
  }

  if guess == 41 or guess == 43 {
    return "So close"
  }

  if guess > 42 {
    return "Too high"
  }

  return "Too low"
}

def reply_cond(guess: Int) -> String {
  cond {
    guess == 42 -> "Correct"
    guess == 41 or guess == 42 -> "So close"
    guess > 42 -> "Too high"
    True -> "Too low"
  }
}

def reply_case(guess: Int) -> String {
  case guess {
    42 -> "Correct"
    41 | 43 -> "So close"
    g if g > 42 -> "Too high"
    _ -> "Too low"
  }
}

pub def main() {
  reply_if(46) |> echo
  reply_cond(42) |> echo
  reply_case(21) |>echo
}

An exercism exercise from the Gleam track, solved in Bea: beacode/src/e5_guessing_game.bea