Skip to content

Commit 6a48b46

Browse files
pm5cuihtlauac
andauthored
Cookbook: Use a Hash Table With Given Key and Value Types (#3165)
* Cookbook: Use a Hash Table With Given Key and Value Types * Apply suggestions from code review * Update data/cookbook/use-hash-table-with-given-key-value-types/00-stdlib.ml --------- Co-authored-by: Cuihtlauac Alvarado <cuihtlauac@users.noreply.github.com>
1 parent e858577 commit 6a48b46

File tree

1 file changed

+55
-0
lines changed
  • data/cookbook/use-hash-table-with-given-key-value-types

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)