|
| 1 | +--- |
| 2 | +packages: [] |
| 3 | +--- |
| 4 | +let open Format in |
| 5 | +(* `Hashtbl.t` is a hash table with in-place modification. |
| 6 | + `Hashtbl.create ( -1 )` creates a table of default size. |
| 7 | + If you know how large the table would become, it is better to set a size on creation. |
| 8 | + But the table grows as needed, so setting the size accurately is technically not necessary. |
| 9 | +*) |
| 10 | +let numbers = Hashtbl.create ( -1 ) in |
| 11 | + |
| 12 | +(* Adds an element `1` to the table with the key `"one"`. *) |
| 13 | +Hashtbl.add numbers "one" 1; |
| 14 | +Hashtbl.add numbers "two" 2; |
| 15 | +Hashtbl.add numbers "three" 3; |
| 16 | +Hashtbl.add numbers "secret" 42; |
| 17 | + |
| 18 | +printf "%i\n%!" (Hashtbl.find numbers "secret"); |
| 19 | + |
| 20 | +(* `Hashtbl.find` looks up for an element by its key. *) |
| 21 | +(try printf "%i\n%!" (Hashtbl.find numbers "four") |
| 22 | + with Not_found -> printf "There is no four.\n%!"); |
| 23 | + |
| 24 | +(* `Hashtbl.find_opt` does the same but returns an `option`. *) |
| 25 | +(match Hashtbl.find_opt numbers "four" with |
| 26 | +| Some value -> printf "%i\n%!" value |
| 27 | +| None -> printf "There is no four.\n%!"); |
| 28 | + |
| 29 | +(* `Hashtbl.add` adds an element, but hides the previous element under the same key. |
| 30 | + The classical bahavior of replacing the previous element under the same key. |
| 31 | +*) |
| 32 | +Hashtbl.add numbers "secret" 543; |
| 33 | +printf "%i\n%!" (Hashtbl.find numbers "secret"); |
| 34 | +(* Removes an element by its key. *) |
| 35 | +Hashtbl.remove numbers "secret"; |
| 36 | +(* The previous values is back. *) |
| 37 | +printf "%i\n%!" (Hashtbl.find numbers "secret"); |
| 38 | + |
| 39 | +(* Replace the previous value. *) |
| 40 | +Hashtbl.replace numbers "secret" 543; |
| 41 | +Hashtbl.remove numbers "secret"; |
| 42 | +(* The element is removed. *) |
| 43 | +(try printf "%i\n%!" (Hashtbl.find numbers "secret") |
| 44 | + with Not_found -> printf "There is no secret.\n%!"); |
| 45 | + |
| 46 | +(* This becomes a bit tideous, so sometimes people define operators. *) |
| 47 | +let ( .%{} ) tbl key = Hashtbl.find tbl key |
| 48 | +and ( .%?{} ) tbl key = Hashtbl.find_opt tbl key |
| 49 | +and ( .%{}<- ) tbl key value = Hashtbl.replace tbl key value |
| 50 | +in |
| 51 | +numbers.%{"secret"} <- 42; |
| 52 | +printf "%i\n%!" numbers.%{"secret"}; |
| 53 | + |
| 54 | +(* Iterate over the whole table. *) |
| 55 | +numbers |> Hashtbl.iter (printf "%s = %i\n%!") |
0 commit comments