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.

Open in playground
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")
}

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