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
- The fold looks up, adds, and re-fronts each pool's total.
List.remove_assocdrops the stale pair before consing.- A comparator flip sorts the totals descending.
Keywords and builtins used here
funinlet
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.
Step 4 of 4 in Lists, step 14 of 29 in Language basics.