```module M = Map.Make(String)

let m0 = M.empty        (* dictionarul vid *)

let m1 = M.singleton "x" 5        (* o singura asociere ("x", 5) *)

let test1 = M.bindings m1        (* produce lista de perechi din dictionar *)

let m2 = M.add "y" 3 m1                (*  asocierea ("y", 3) plus cele din m1 *)

let t11 = M.bindings m1                (* a ramas la fel *)

let t2 = M.bindings m2                (* [("x", 5); ("y", 3)] *)

let m3 = M.add "x" 2 m2                (* noua asociere pentru x o înlocuiește pe cea veche *)

let test3 = M.bindings m3        (* [("x", 2); ("y", 3)]        *)

let m4 = M.remove "x" m3        (* elimină "x" și valoarea asociată *)

let test4 = M.bindings m3        (* [("y", 3)] *)

let t41 = M.remove "z" m2 |> M.bindings  (* nu contine "z", nu are efect *)

(* val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b *)
(* functia de parcurgere are 3 param: cheie si valoare din dictionar, acumulator *)

let cardinal m = M.fold (fun k v acc -> acc + 1) m 0 (* numarul de perechi: functie standard *)

let t5 = cardinal m2

(* lista de perechi din asociere, acumulata in ordinea inversa parcurgerii *)
let rev_bindings m = M.fold (fun k v acc -> (k, v)::acc) m []

(* functie standard, poate fi scrisa cu fold *)
let bindings m = M.fold (fun k v acc -> (k, v)::acc) m [] |> List.rev

let t6 = bindings m2

let t7 = M.find "x" m2
let t8 = M.find "z" m2        (* exceptie *)

let myfind k m = try M.find k m                (* da 13 pentru orice cheie negasita *)
with Not_found -> 13

let t9 = myfind "z" m2

let exc_when_found x lst = List.iter (fun e -> if x = e then raise Exit) lst

let t_noexc = exc_when_found 3 [2;4;5]

let t_exc = exc_when_found 4 [2;4;5]

let mem x lst = try List.iter (fun e -> if x = e then raise Exit) lst; false
with Exit -> true

let t10 = mem 4 [2;4;5]

let plist = [("x", 5); ("y", 3); ("x", 2); ("a", 2)]

(* creeaza dictionar, pastreaza ultima valoare pentru fiecare cheie *)
let of_list_last lst = List.fold_left (fun dict (k, v) -> M.add k v dict) M.empty lst

let t11 = of_list_last plist |> M.bindings  (* [("a", 2); ("x", 2); ("y", 3)] *)

(* creeaza dictionar, pastreaza prima valoare pentru fiecare cheie *)
let of_list_first lst = List.fold_left
(fun dict (k, v) -> if M.mem k dict then dict
else M.add k v dict) M.empty lst

let t12 = of_list_first plist |> M.bindings (* [("a", 2); ("x", 5); ("y", 3)] *)

(* creeaza dictionar, pastreaza toate valorile ca lista *)
let addnew dict (k,v) = let lst = try M.find k dict
with Not_found -> []
in M.add k (v :: lst) dict

let of_list_all lst = List.fold_left addnew M.empty lst

let t13 = of_list_all plist |> M.bindings      (* [("a", [2]); ("x", [2; 5]); ("y", [3])] *)

```

This document was generated using caml2html