Title here
Summary here
Maps are a built-in associative data type (sometimes called hashes or dicts in other languages).
let () =
(* Create an empty map *)
let m = Hashtbl.create 10 in
(* Set key/value pairs *)
Hashtbl.add m "k1" 7;
Hashtbl.add m "k2" 13;
(* Printing a map will show all of its key/value pairs *)
let print_map m =
Hashtbl.iter (fun k v -> Printf.printf "%s: %d\n" k v) m
in
Printf.printf "map:\n";
print_map m;
(* Get a value for a key *)
let v1 = Hashtbl.find_opt m "k1" in
Printf.printf "v1: %s\n" (match v1 with Some v -> string_of_int v | None -> "None");
(* If the key doesn't exist, None is returned *)
let v3 = Hashtbl.find_opt m "k3" in
Printf.printf "v3: %s\n" (match v3 with Some v -> string_of_int v | None -> "None");
(* The length of a map (number of key/value pairs) *)
Printf.printf "len: %d\n" (Hashtbl.length m);
(* Remove a key/value pair from a map *)
Hashtbl.remove m "k2";
Printf.printf "map (after deletion):\n";
print_map m;
(* To clear all key/value pairs from a map *)
Hashtbl.reset m;
Printf.printf "map (after clear):\n";
print_map m;
(* Check if a key is present in the map *)
Hashtbl.add m "k2" 13;
let prs = Hashtbl.find_opt m "k2" in
Printf.printf "prs: %b\n" (match prs with Some _ -> true | None -> false);
(* Declare and initialize a new map *)
let n = Hashtbl.create 10 in
Hashtbl.add n "foo" 1;
Hashtbl.add n "bar" 2;
Printf.printf "map (new map):\n";
print_map n;
(* Check equality of two maps *)
let n2 = Hashtbl.create 10 in
Hashtbl.add n2 "foo" 1;
Hashtbl.add n2 "bar" 2;
if Hashtbl.equal (=) n n2 then
Printf.printf "n == n2\n"
else
Printf.printf "n != n2\n"
To run the program, put the code in maps.ml
and use the OCaml compiler.
$ ocamlc -o maps maps.ml
$ ./maps
map:
k1: 7
k2: 13
v1: 7
v3: None
len: 2
map (after deletion):
k1: 7
map (after clear):
prs: true
map (new map):
foo: 1
bar: 2
n == n2
Now that we can run and build basic OCaml programs, let’s learn more about the language.