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
Hashtbl.replacewrites; a second replace overwrites.Hashtbl.findthrows;find_optreturns an option.List.assoc_optreads an association list safely.
Keywords and builtins used here
NoneSomeinletmatchwith
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.
Step 1 of 4 in Collections, step 18 of 29 in Language basics.