TIL: No `if`s in Gleam
·
Yan Yi Goh·
2 min read
Gleam does not have an if
statement. The Exercism exercise required me to return a custom type based on whether it’s True
or False
.
pub fn get_treasure(
chest: TreasureChest(treasure),
password: String,
) -> UnlockResult(treasure) {
case chest.password == password {
True -> Unlocked(chest.value)
False -> WrongPassword
}
}
Now, trying alternatives, I came up with the following with bool.guard to get things to still work:
pub fn get_treasure(
chest: TreasureChest(treasure),
password: String,
) -> UnlockResult(treasure) {
{ chest.password == password }
|> bool.guard(return: Unlocked(chest.value), otherwise: fn() { WrongPassword } )
}
Not as readable, in my opinion. Or, following the gleam/bool
documentation with use
, I could do the following like how I early-return in Go:
pub fn get_treasure(
chest: TreasureChest(treasure),
password: String,
) -> UnlockResult(treasure) {
use <- bool.guard(when: chest.password == password, return: Unlocked(chest.value))
WrongPassword
}
The syntax looks wonky 😵💫 (just like me being a noob reading Rust code). Need to write more Gleam. Here’s a Go comparison where the language often promotes early-returns:
// Go does not have sum type, so I am just giving an arbitary example for early returns.
func getTreasure(chest: TreasureChest, password: string) UnlockResult {
if chest.password == password {
return Unlocked{ value: chest.value }
}
return WrongPassword
}