typestar

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

  1. countBy id tallies the words in a single pass.
  2. Sorting by (-n, word) ranks with alphabetical ties.
  3. String.replicate n "#" draws each bar.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →