TExcelTAD
Home › OCaml › OCaml Map and Set

OCaml Map and Set

Map and Set are the standard immutable collections for looking things up by key. They are balanced binary search trees, so lookups, insertions and removals take O(log n) time, and every operation returns a new map or set while the old one stays valid.

You create them with the functors Map.Make and Set.Make, giving the key type:

ocaml
module SMap = Map.Make (String)   (* maps with string keys *)
module ISet = Set.Make (Int)      (* sets of ints *)

Map basics

ocaml · try it yourself
module SMap = Map.Make (String)

let () =
  let stock = SMap.empty |> SMap.add "apples" 12 |> SMap.add "pears" 4 |> SMap.add "kiwis" 30 in
  Printf.printf "pears: %d\n" (SMap.find "pears" stock);
  Printf.printf "has plums: %b\n" (SMap.mem "plums" stock);
  Printf.printf "plums: %d\n" (Option.value (SMap.find_opt "plums" stock) ~default:0);
  let stock2 = stock |> SMap.add "pears" 10 |> SMap.remove "kiwis" in
  Printf.printf "size before %d, after %d\n" (SMap.cardinal stock) (SMap.cardinal stock2);
  SMap.iter (Printf.printf "  %s=%d\n") stock2
pears: 4
has plums: false
plums: 0
size before 3, after 2
  apples=12
  pears=10

add replaces the value if the key already exists. find raises Not_found for a missing key; find_opt returns an option.

Counting with update

SMap.update key f map calls f with the current value (Some v or None) and stores what f returns (None removes the key). It is the cleanest way to count:

ocaml · try it yourself
module SMap = Map.Make (String)

let word_counts text =
  String.split_on_char ' ' text
  |> List.filter (fun w -> w <> "")
  |> List.fold_left
       (fun m w ->
         SMap.update (String.lowercase_ascii w) (function None -> Some 1 | Some n -> Some (n + 1)) m)
       SMap.empty

let () =
  let counts = word_counts "the cat and the hat and THE bat" in
  SMap.iter (fun w n -> Printf.printf "%-4s %d\n" w n) counts;
  let top_word, top_n =
    SMap.fold (fun w n (bw, bn) -> if n > bn then (w, n) else (bw, bn)) counts ("", 0)
  in
  Printf.printf "most common: %s (%d)\n" top_word top_n
and  2
bat  1
cat  1
hat  1
the  3
most common: the (3)

Transforming maps

ocaml · try it yourself
module SMap = Map.Make (String)

let () =
  let prices = SMap.of_seq (List.to_seq [ ("tea", 3.5); ("cake", 4.0); ("water", 1.0) ]) in
  let with_tip = SMap.map (fun p -> p *. 1.1) prices in
  let cheap = SMap.filter (fun _ p -> p < 2.0) prices in
  SMap.iter (Printf.printf "%s %.2f\n") with_tip;
  print_endline (String.concat "," (List.map fst (SMap.bindings cheap)));
  let total = SMap.fold (fun _ p acc -> acc +. p) prices 0.0 in
  Printf.printf "total %.2f\n" total;
  match SMap.min_binding_opt prices with
  | Some (k, _) -> Printf.printf "first key: %s\n" k
  | None -> ()
cake 4.40
tea 3.85
water 1.10
water
total 8.50
first key: cake

bindings returns the (key, value) pairs as a sorted list.

Set basics

A Set holds unique elements in sorted order and supports the usual set algebra:

ocaml · try it yourself
module SSet = Set.Make (String)

let show s = "{" ^ String.concat ", " (SSet.elements s) ^ "}"

let () =
  let alice = SSet.of_list [ "rust"; "ocaml"; "python" ] in
  let bob = SSet.of_list [ "python"; "go"; "ocaml"; "ocaml" ] in
  print_endline (show bob);
  print_endline ("both:   " ^ show (SSet.inter alice bob));
  print_endline ("either: " ^ show (SSet.union alice bob));
  print_endline ("only alice: " ^ show (SSet.diff alice bob));
  Printf.printf "%b %b %d\n" (SSet.mem "go" bob) (SSet.subset (SSet.singleton "go") bob) (SSet.cardinal alice)
{go, ocaml, python}
both:   {ocaml, python}
either: {go, ocaml, python, rust}
only alice: {rust}
true true 3

Removing duplicates while keeping order

A set is perfect for "have I seen this before?" checks:

ocaml · try it yourself
module ISet = Set.Make (Int)

let dedup_keep_order lst =
  let _, kept =
    List.fold_left
      (fun (seen, acc) x -> if ISet.mem x seen then (seen, acc) else (ISet.add x seen, x :: acc))
      (ISet.empty, []) lst
  in
  List.rev kept

let () =
  dedup_keep_order [ 4; 1; 4; 2; 1; 9; 2 ] |> List.map string_of_int |> String.concat " " |> print_endline
4 1 2 9

Map, Set, Hashtbl or association list?

Collection Mutable? Lookup Ordered iteration Best for
association list no O(n) insertion order a handful of items
Map no O(log n) sorted by key most keyed data in functional code
Set no O(log n) sorted membership, set algebra
Hashtbl yes O(1) average unspecified large, frequently updated tables

Test yourself

After let m2 = SMap.add "k" 1 m1, what happens to m1?

  1. It also contains "k"
  2. It is unchanged
  3. It is deleted
  4. It raises an exception

What does SMap.find "missing" m do when the key is absent?

  1. Returns None
  2. Returns a default value
  3. Raises Not_found
  4. Returns 0

Which function returns the elements present in both sets?

  1. union
  2. diff
  3. inter
  4. subset