typestar

The List module in OCaml

map, filter, sort, fold_left: the daily toolkit.

(* The List module is the daily toolkit: map, filter, sort. *)
let survey = [("north", 12); ("ledge", 31); ("cove", 5)]

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

  let total = List.fold_left (fun acc (_, n) -> acc + n) 0 survey in
  Printf.printf "Total animals: %d\n" total;

  let busy = List.filter (fun (_, n) -> n > 10) survey in
  busy |> List.map fst |> String.concat ", "
       |> Printf.printf "Above ten: %s\n"

How it works

  1. List.sort takes a comparator; flipping it sorts descending.
  2. fold_left sums a field across tuples.
  3. filter then map fst extracts the busy pool names.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
497
Tokens
156
Three-star pace
60 tpm

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

Type this snippet

Step 2 of 4 in Lists, step 12 of 29 in Language basics.

← Previous Next →

The List module in other languages