typestar

word_freq.ml in OCaml

A word-frequency table from split_on_char, a Hashtbl, and one 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"

let () =
  let counts = Hashtbl.create 16 in
  String.split_on_char ' ' passage
  |> List.iter (fun word ->
      let n = Option.value ~default:0 (Hashtbl.find_opt counts word) in
      Hashtbl.replace counts word (n + 1));

  (* Pull the pairs out and rank: count descending, ties by word. *)
  let ranked =
    Hashtbl.fold (fun word n acc -> (word, n) :: acc) counts []
    |> List.sort (fun (w1, n1) (w2, n2) ->
        if n1 <> n2 then compare n2 n1 else compare w1 w2)
  in

  Printf.printf "%d distinct words\n" (List.length ranked);
  print_endline "word    ct bar";
  ranked
  |> List.iter (fun (word, n) ->
      Printf.printf "%-7s %2d %s\n" word n (String.make n '#'))

How it works

  1. Hashtbl.find_opt with a default tallies each word.
  2. Hashtbl.fold pulls the pairs out for ranking.
  3. String.make n '#' draws each word's bar.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
790
Tokens
176
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 176 seconds.

Type this snippet

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

← Previous Next →