typestar

Grouping in OCaml

Group by key with a fold into an assoc list, then rank.

(* Group by key with a fold into an assoc list, then rank. *)
let sightings =
  [("north", 12); ("ledge", 31); ("north", 8); ("cove", 5);
   ("ledge", 4)]

let totals =
  List.fold_left
    (fun acc (pool, n) ->
       let so_far = Option.value ~default:0 (List.assoc_opt pool acc) in
       (pool, so_far + n) :: List.remove_assoc pool acc)
    [] sightings

let () =
  totals
  |> List.sort (fun (_, a) (_, b) -> compare b a)
  |> List.iter (fun (pool, n) -> Printf.printf "%-6s %3d\n" pool n)

How it works

  1. The fold looks up, adds, and re-fronts each pool's total.
  2. List.remove_assoc drops the stale pair before consing.
  3. A comparator flip sorts the totals descending.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
460
Tokens
145
Three-star pace
60 tpm

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

Type this snippet

Step 4 of 4 in Lists, step 14 of 29 in Language basics.

← Previous Next →