TExcelTAD
Home › OCaml › OCaml List Module

OCaml List Module

The standard List module contains dozens of ready-made functions. Knowing them saves you from writing the same recursive functions again and again. This lesson tours the most useful ones; the higher-order trio map, filter and fold gets its own lesson later.

Inspecting lists

ocaml · try it yourself
let scores = [ 72; 95; 58; 88; 95 ]

let () =
  Printf.printf "length: %d\n" (List.length scores);
  Printf.printf "has 58: %b\n" (List.mem 58 scores);
  Printf.printf "any above 90: %b\n" (List.exists (fun s -> s > 90) scores);
  Printf.printf "all passing: %b\n" (List.for_all (fun s -> s >= 60) scores);
  Printf.printf "first above 80: %d\n" (List.find (fun s -> s > 80) scores);
  (match List.find_opt (fun s -> s > 100) scores with
   | Some s -> Printf.printf "found %d\n" s
   | None -> print_endline "nobody above 100")
length: 5
has 58: true
any above 90: true
all passing: false
first above 80: 95
nobody above 100

List.find raises Not_found when nothing matches; List.find_opt returns an option instead. Many functions come in both flavours.

Sorting

List.sort takes a comparison function. The generic compare sorts in ascending order; flip the arguments for descending:

ocaml · try it yourself
let show lst = String.concat " " (List.map string_of_int lst)

let () =
  let nums = [ 5; 2; 9; 2; 7 ] in
  print_endline (show (List.sort compare nums));
  print_endline (show (List.sort (fun a b -> compare b a) nums));
  print_endline (show (List.sort_uniq compare nums));
  let words = [ "pear"; "fig"; "banana"; "kiwi"; "apple" ] in
  let by_length = List.sort (fun a b -> compare (String.length a) (String.length b)) words in
  print_endline (String.concat " " by_length)
2 2 5 7 9
9 7 5 2 2
2 5 7 9
fig pear kiwi apple banana

List.sort is a stable merge sort: elements that compare equal keep their original order, so "pear" stays before "kiwi" (both have 4 letters). List.sort_uniq also removes duplicates.

Association lists

A list of (key, value) pairs is an association list, a simple dictionary for small data:

ocaml · try it yourself
let capitals = [ ("France", "Paris"); ("Japan", "Tokyo"); ("Peru", "Lima") ]

let () =
  print_endline (List.assoc "Japan" capitals);
  Printf.printf "%b\n" (List.mem_assoc "Chile" capitals);
  (match List.assoc_opt "Chile" capitals with
   | Some c -> print_endline c
   | None -> print_endline "unknown country");
  let countries, cities = List.split capitals in
  print_endline (String.concat "," countries);
  print_endline (String.concat "," cities)
Tokyo
false
unknown country
France,Japan,Peru
Paris,Tokyo,Lima

Lookups are O(n), so for larger data use Map or Hashtbl (later lessons).

Combining and splitting

ocaml · try it yourself
let show lst = "[" ^ String.concat "; " (List.map string_of_int lst) ^ "]"

let () =
  let evens, odds = List.partition (fun n -> n mod 2 = 0) [ 1; 2; 3; 4; 5; 6 ] in
  print_endline (show evens ^ " " ^ show odds);
  let pairs = List.combine [ 1; 2; 3 ] [ "a"; "b"; "c" ] in
  List.iter (fun (n, s) -> Printf.printf "%d%s " n s) pairs;
  print_newline ();
  print_endline (show (List.filteri (fun i _ -> i < 3) [ 10; 20; 30; 40 ]));
  List.iteri (fun i name -> Printf.printf "%d. %s\n" (i + 1) name) [ "setup"; "build"; "test" ]
[2; 4; 6] [1; 3; 5]
1a 2b 3c 
[10; 20; 30]
1. setup
2. build
3. test

List.combine raises Invalid_argument if the lists have different lengths.

Reference table

Function What it does
length, hd, tl, nth, rev basics
mem x l, exists p l, for_all p l membership tests
find p l, find_opt p l, filter p l search
sort cmp l, sort_uniq cmp l, stable_sort sorting
assoc k l, assoc_opt, mem_assoc, remove_assoc association lists
split, combine, partition split and join
init n f, concat, flatten, append (@) building
iter f l, iteri f l side effects for each element
map, mapi, filter_map, concat_map transforming
fold_left, fold_right reducing to one value
equal, compare compare two lists with a custom element function

Test yourself

What does List.find_opt (fun x -> x > 10) [1; 2] return?

  1. 0
  2. None
  3. It raises Not_found
  4. []

How do you sort a list of ints in descending order?

  1. List.sort compare l
  2. List.sort (fun a b -> compare b a) l
  3. List.rev_sort l
  4. List.sort (-) l |> List.tl

What does List.partition (fun x -> x > 2) [1; 3; 2; 4] return?

  1. ([3; 4], [1; 2])
  2. ([1; 2], [3; 4])
  3. [3; 4]
  4. ([3], [4])