TExcelTAD
Home › OCaml › OCaml Hashtables

OCaml Hashtables

Hashtbl is OCaml's mutable hash table: a dictionary with O(1) average-time lookups and updates. Use it when you have a lot of keyed data that changes often and you don't need the old versions (unlike the immutable Map).

ocaml · try it yourself
let () =
  let phone_book : (string, string) Hashtbl.t = Hashtbl.create 16 in
  Hashtbl.replace phone_book "Ada" "555-0101";
  Hashtbl.replace phone_book "Linus" "555-0199";
  Hashtbl.replace phone_book "Ada" "555-0102";   (* replace overwrites *)
  Printf.printf "Ada: %s\n" (Hashtbl.find phone_book "Ada");
  Printf.printf "entries: %d\n" (Hashtbl.length phone_book);
  Printf.printf "has Grace: %b\n" (Hashtbl.mem phone_book "Grace");
  (match Hashtbl.find_opt phone_book "Grace" with
   | Some n -> print_endline n
   | None -> print_endline "Grace: unknown");
  Hashtbl.remove phone_book "Linus";
  Printf.printf "entries after remove: %d\n" (Hashtbl.length phone_book)
Ada: 555-0102
entries: 2
has Grace: false
Grace: unknown
entries after remove: 1

Hashtbl.create n makes an empty table; n is only an initial size hint, and the table grows automatically. The type (string, string) Hashtbl.t means "keys are strings, values are strings". The annotation is optional: OCaml infers it from the first use.

add versus replace

This is the most common Hashtbl surprise. Hashtbl.add does not overwrite: it pushes a new binding that hides the old one, and remove brings the old one back. Hashtbl.replace overwrites. For a normal dictionary, always use replace.

ocaml · try it yourself
let () =
  let t = Hashtbl.create 4 in
  Hashtbl.add t "color" "red";
  Hashtbl.add t "color" "blue";
  Printf.printf "find: %s, length: %d\n" (Hashtbl.find t "color") (Hashtbl.length t);
  Printf.printf "all: %s\n" (String.concat "," (Hashtbl.find_all t "color"));
  Hashtbl.remove t "color";
  Printf.printf "after remove: %s\n" (Hashtbl.find t "color")
find: blue, length: 2
all: blue,red
after remove: red

Iteration order is not defined

Hashtbl.iter and Hashtbl.fold visit entries in an unspecified order that depends on the hash function and the table size. Never rely on it. When the output must be stable, collect the entries and sort them:

ocaml · try it yourself
let () =
  let counts = Hashtbl.create 32 in
  "mississippi"
  |> String.iter (fun c ->
         let n = Option.value (Hashtbl.find_opt counts c) ~default:0 in
         Hashtbl.replace counts c (n + 1));
  let pairs = Hashtbl.fold (fun k v acc -> (k, v) :: acc) counts [] in
  let sorted = List.sort compare pairs in
  List.iter (fun (c, n) -> Printf.printf "%c: %d\n" c n) sorted
i: 4
m: 1
p: 2
s: 4

Hashtbl.to_seq_keys, to_seq_values and to_seq give the contents as sequences, which you can turn into lists with List.of_seq and then sort.

Memoization

A classic use of hash tables is caching the results of an expensive function. Here the naive Fibonacci function becomes fast:

ocaml · try it yourself
let memo_fib =
  let cache = Hashtbl.create 64 in
  let rec fib n =
    if n < 2 then n
    else
      match Hashtbl.find_opt cache n with
      | Some v -> v
      | None ->
          let v = fib (n - 1) + fib (n - 2) in
          Hashtbl.replace cache n v;
          v
  in
  fib

let () =
  Printf.printf "fib 80 = %d\n" (memo_fib 80);
  Printf.printf "fib 40 = %d\n" (memo_fib 40)
fib 80 = 23416728348467685
fib 40 = 102334155

Each fib n is computed once, so fib 80 takes about 80 steps instead of billions.

Grouping

ocaml · try it yourself
let () =
  let words = [ "apple"; "avocado"; "banana"; "blueberry"; "cherry"; "apricot" ] in
  let groups = Hashtbl.create 8 in
  List.iter
    (fun w ->
      let key = w.[0] in
      let existing = Option.value (Hashtbl.find_opt groups key) ~default:[] in
      Hashtbl.replace groups key (w :: existing))
    words;
  Hashtbl.to_seq groups |> List.of_seq |> List.sort compare
  |> List.iter (fun (k, ws) -> Printf.printf "%c: %s\n" k (String.concat ", " (List.rev ws)))
a: apple, avocado, apricot
b: banana, blueberry
c: cherry

Custom keys and Hashtbl.Make

The generic Hashtbl uses structural hashing (Hashtbl.hash) and equality (=), which work for ints, strings, tuples and records. For keys that need a different notion of equality, such as case-insensitive strings, use the functor Hashtbl.Make:

ocaml · try it yourself
module CaseInsensitive = Hashtbl.Make (struct
  type t = string
  let equal a b = String.lowercase_ascii a = String.lowercase_ascii b
  let hash s = Hashtbl.hash (String.lowercase_ascii s)
end)

let () =
  let headers = CaseInsensitive.create 8 in
  CaseInsensitive.replace headers "Content-Type" "text/html";
  print_endline (CaseInsensitive.find headers "content-type");
  print_endline (CaseInsensitive.find headers "CONTENT-TYPE")
text/html
text/html

Warning: Hashtbl is not safe to modify from several domains at once. In parallel code, protect it with a Mutex or give each domain its own table.

Test yourself

Which function overwrites an existing key in a Hashtbl?

  1. Hashtbl.add
  2. Hashtbl.replace
  3. Hashtbl.set
  4. Hashtbl.update

In what order does Hashtbl.iter visit the entries?

  1. Insertion order
  2. Sorted by key
  3. Unspecified
  4. Reverse insertion order

What does Hashtbl.find t k do if k is absent?

  1. Returns None
  2. Raises Not_found
  3. Returns a default
  4. Adds the key