You will use
pooka/dict:dict.empty(), and the methodsget_or,insert,keys,getpooka/list:fold,sort_by,grouppooka/string:string.comparefor alphabetical order
The whole program
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
- Dicts never change.
counts.insert(vote, …)returns a newDictwith one more entry; the old one is untouched. That is why the tally is afold: each step hands the newer dict to the next. get_orsaves amatch.counts.get_or(vote, 0)is the count so far, or0for a drink nobody has asked for yet.- Order is up to you. A
Dictkeeps no particular order, so sort its keys before printing anything a person will read. list.groupbuilds a dict of lists. Give it a function that names each item's jar (here, the first letter) and it returnsDict(String, List(String)).getreturns anOption, 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.