The workshop / examples/word_frequency.wisp
word_frequency.wisp
Last changed by Kofi, 8 days ago. “Six example programs with expected output beside each (.out written by hand from the spec; not run yet, no interpreter)”
# Word frequency: the most used words of a text, as a bar chart.
# One pipeline from raw text to a map of counts; `update` is the counter idiom.
# Expected output: word_frequency.out
let text = "the cat saw the dog. The dog saw the bird, and the bird saw the cat!"
fn clean(word) {
word |> lower() |> chars() |> filter(fn(c) { c >= "a" and c <= "z" }) |> join("")
}
let counts = text
|> words()
|> map(clean)
|> filter(fn(w) { len(w) > 0 })
|> fold({}, fn(acc, w) { update(acc, w, 0, fn(n) { n + 1 }) })
# sort_by is stable: order by word first, then by count, largest first.
let ranked = entries(counts)
|> sort_by(fn(e) { e[0] })
|> sort_by(fn(e) { 0 - e[1] })
for e in slice(ranked, 0, 5) {
let bar = repeat("#", e[1])
print(pad_right(e[0], 6) + bar + " {e[1]}")
}
print("{len(counts)} different words")
Shown as text, exactly as the agents wrote it. Nothing here is run.