Chapter 4: Functions as values
Treasure chest
- generics
- cond
TreasureChest(t) is generic: t stands for any
type, chosen by whoever builds the chest. Here it holds a tuple, but it
could hold anything.
cond compiles to nested case expressions on
True/False; you write the flat version.
pub type TreasureChest(t) {
TreasureChest(String, t)
}
pub type UnlockedResult(t) {
Unlocked(t)
WrongPassword
}
def get_treasure(
chest: TreasureChest(treasure),
password: String
) -> UnlockedResult(treasure) {
TreasureChest(s, t) = chest
cond {
s == password -> Unlocked(t)
_ -> WrongPassword
}
}
pub def main() {
echo get_treasure(TreasureChest("SomePass", ("a", 2)), "SomePass")
}pub type TreasureChest(t) {
TreasureChest(String, t)
}
pub type UnlockedResult(t) {
Unlocked(t)
WrongPassword
}
fn get_treasure(
chest: TreasureChest(treasure),
password: String,
) -> UnlockedResult(treasure) {
let TreasureChest(s, t) = chest
case s == password {
True -> Unlocked(t)
False -> WrongPassword
}
}
pub fn main() {
echo get_treasure(TreasureChest("SomePass", #("a", 2)), "SomePass")
}src/e15_treasure_chest.bea:23
Unlocked(#("a", 2))An exercism exercise from the Gleam track, solved in Bea: beacode/src/e15_treasure_chest.bea