← Cookbook Collections Beginner · Pooka 0.5.0

Count things with a Dict

A Dict is a cupboard of labelled jars. Count votes into it, read the counts back in order, and let list.group sort things into jars for you.

You will use

  • pooka/dict: dict.empty(), and the methods get_or, insert, keys, get
  • pooka/list: fold, sort_by, group
  • pooka/string: string.compare for alphabetical order

The whole program

src/main.pooka
module main

import pooka/dict.{Dict}
import pooka/int
import pooka/io
import pooka/list
import pooka/string

tally(votes: List(String)) -> Dict(String, Int) {
  list.fold(votes, dict.empty(), fn(counts: Dict(String, Int), vote: String) {
    counts.insert(vote, counts.get_or(vote, 0) + 1)
  })
}

main() {
  let votes = ["tea", "cocoa", "tea", "coffee", "tea", "cocoa"]
  let counts = tally(votes)
  counts.keys()
  |> list.sort_by(string.compare)
  |> list.each(fn(drink: String) {
    io.println(drink + ": " + int.to_string(counts.get_or(drink, 0)))
    Nil
  })

  let by_letter = list.group(
    ["owl", "otter", "fox", "finch", "hare"],
    fn(
      animal: String
    ) {
      string.slice(animal, 0, 1)
    }
  )
  echo by_letter.get("f")
}

Run it

$ pooka run
cocoa: 2
coffee: 1
tea: 3
src/main.pooka:33
Some(["fox", "finch"])

How it works

  1. Dicts never change. counts.insert(vote, …) returns a new Dict with one more entry; the old one is untouched. That is why the tally is a fold: each step hands the newer dict to the next.
  2. get_or saves a match. counts.get_or(vote, 0) is the count so far, or 0 for a drink nobody has asked for yet.
  3. Order is up to you. A Dict keeps no particular order, so sort its keys before printing anything a person will read.
  4. list.group builds a dict of lists. Give it a function that names each item's jar (here, the first letter) and it returns Dict(String, List(String)). get returns an Option, because the jar might not exist.

Try next: upsert does the read and the write in one call; Count words in a file uses it. dict.from_list builds a dict from pairs in one go.