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.
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
}import gleam/bool
fn reply_if(guess: Int) -> String {
use <- bool.guard(when: guess == 42, return: "Correct")
use <- bool.guard(when: guess == 41 || guess == 43, return: "So close")
use <- bool.guard(when: guess > 42, return: "Too high")
"Too low"
}
fn reply_cond(guess: Int) -> String {
case guess == 42 {
True -> "Correct"
False ->
case guess == 41 || guess == 42 {
True -> "So close"
False ->
case guess > 42 {
True -> "Too high"
False -> "Too low"
}
}
}
}
fn reply_case(guess: Int) -> String {
case guess {
42 -> "Correct"
41 | 43 -> "So close"
g if g > 42 -> "Too high"
_ -> "Too low"
}
}
pub fn main() {
reply_if(46) |> echo
reply_cond(42) |> echo
reply_case(21) |> echo
}src/e5_guessing_game.bea:36
"Too high"
src/e5_guessing_game.bea:37
"Correct"
src/e5_guessing_game.bea:38
"Too low"An exercism exercise from the Gleam track, solved in Bea: beacode/src/e5_guessing_game.bea