Chapter 5: Collections

High score board

  • dicts
  • type aliases
  • Option

pub type Scores = Dict(String, Int) gives a long type a short name.

Some, None and Dict appear without any import: Bea adds the right imports for standard library names when you use them, and it is scope aware, so a variable called list is never mistaken for the module.

Open in playground
import gleam/dict

pub type Scores = Dict(String, Int)

def create_score_board() {
  %{"The Best Ever": 1_000_000}
}

def add_player(scores: Scores, name: String, score: Int) -> Scores {
  dict.insert(scores, name, score)
}

def remove_player(scores: Scores, name: String) -> Scores {
  dict.delete(scores, name)
}

def update_score(scores: Scores, name: String, score: Int) -> Scores {
  update_fn = fn(x) {
    case x {
      Some(value) -> value + score
      None -> score
    }
  }
  dict.upsert(scores, name, update_fn)
}

def apply_monday_bonus(scores: Scores) -> Scores {
  dict.map_values(scores, fn(_k, v) { v  + 100 })
}

pub def main() {
  create_score_board()
  |> add_player("James Pazo", 12)
  |> remove_player("James Pazo")
  |> update_score("The Best Ever", 3)
  |> apply_monday_bonus()
  |> echo
}

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