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.
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
}import gleam/dict.{type Dict}
import gleam/option.{None, Some}
pub type Scores =
Dict(String, Int)
fn create_score_board() {
dict.from_list([#("The Best Ever", 1_000_000)])
}
fn add_player(scores: Scores, name: String, score: Int) -> Scores {
dict.insert(scores, name, score)
}
fn remove_player(scores: Scores, name: String) -> Scores {
dict.delete(scores, name)
}
fn update_score(scores: Scores, name: String, score: Int) -> Scores {
let update_fn = fn(x) {
case x {
Some(value) -> value + score
None -> score
}
}
dict.upsert(scores, name, update_fn)
}
fn apply_monday_bonus(scores: Scores) -> Scores {
dict.map_values(scores, fn(_k, v) { v + 100 })
}
pub fn main() {
create_score_board()
|> add_player("James Pazo", 12)
|> remove_player("James Pazo")
|> update_score("The Best Ever", 3)
|> apply_monday_bonus()
|> echo
}src/e17_high_score_board.bea:37
dict.from_list([#("The Best Ever", 1000103)])An exercism exercise from the Gleam track, solved in Bea: beacode/src/e17_high_score_board.bea