Home / Docs / Guides

Maps

Release v0.4.0

Map[K, V] maps keys to values, in ascending key order (spec/21). It is a value, as a list is.

una
module words

--- How often each word occurs.
pub counts(words: List[Text]) -> Map[Text, Int]
=
  let edit counts: Map[Text, Int] = empty_map()
  for word in words
    let n = counts.get(key: word)
      if none use 0
    edit counts.set(key: word, value: n + 1)
  counts

--- The words seen at least `least` times, in ascending order.
pub frequent(counts: Map[Text, Int], least: Int) -> List[Text]
=
  let kept = counts.entries().filter(keep: fn(e) -> e.value >= least)
  kept.map(each: fn(e) -> e.key)

--- The count of a word the map has.
pub count_of(counts: Map[Text, Int], word: Text) -> Int
  requires counts.has(key: word)
=
  let n = counts.get(key: word)
    if none use 0
  n
una
-- fails with U2002
module demo

pub empty_counts() -> Map[Text, Nat] = empty_map()