typestar

Hashtbl and assoc lists in OCaml

The mutable map, and the immutable habit for small data.

(* Hashtbl is the mutable map; assoc lists are the immutable habit. *)
let tally = Hashtbl.create 8

let () =
  Hashtbl.replace tally "limpet" 40;
  Hashtbl.replace tally "anemone" 12;
  Hashtbl.replace tally "limpet" 43;  (* replace overwrites *)
  Printf.printf "Limpets: %d\n" (Hashtbl.find tally "limpet");
  Printf.printf "Species tracked: %d\n" (Hashtbl.length tally);

  (* An assoc list does the same job immutably for small data. *)
  let notes = [("north", "clear"); ("ledge", "surge")] in
  match List.assoc_opt "ledge" notes with
  | Some note -> print_endline ("Ledge: " ^ note)
  | None -> print_endline "Ledge unsampled"

How it works

  1. Hashtbl.replace writes; a second replace overwrites.
  2. Hashtbl.find throws; find_opt returns an option.
  3. List.assoc_opt reads an association list safely.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
615
Tokens
130
Three-star pace
60 tpm

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

Type this snippet

Step 1 of 4 in Collections, step 18 of 29 in Language basics.

← Previous Next →