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
List.sorttakes a comparator; flipping it sorts descending.fold_leftsums a field across tuples.filterthenmap fstextracts the busy pool names.
Keywords and builtins used here
funinlet
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.
Step 2 of 4 in Lists, step 12 of 29 in Language basics.