word_freq.fsx in F#
A word-frequency table from Split, countBy, and one two-key sort.
// Count word frequencies in a passage and chart the leaders.
let passage =
"the rain in maine falls mainly on the plain and "
+ "the rain stays on the plain"
// countBy tallies in one pass; a two-key sort ranks the result.
let ranked =
passage.Split ' '
|> Array.toList
|> List.countBy id
|> List.sortBy (fun (word, n) -> (-n, word))
printfn "%d distinct words" (List.length ranked)
printfn "word ct bar"
for word, n in ranked do
printfn "%-7s %2d %s" word n (String.replicate n "#")
How it works
countBy idtallies the words in a single pass.- Sorting by
(-n, word)ranks with alphabetical ties. String.replicate n "#"draws each bar.
Keywords and builtins used here
doforfuninlet
The run, in numbers
- Lines
- 17
- Characters to type
- 490
- Tokens
- 86
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 79 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.