There are some pervasive modules in OCaml that have ready-made functors that may, or must be used to employ the related library functions. Suppose that we want something a bit like a file directory that is indexed by character strings. In other words we want a source of tabulated functions whose domain is strings. We can write:
module Ms = Map.Make(String);;
We have thus created a module which is a source of maps having in common that they are indexed by strings. We can now make such a small map thus:
let s1 = Ms.add "one" 1 Ms.empty;;
let s2 = Ms.add "two" 2 s1;;
We now have a map s2 from the first two English names for numbers, to the numbers themselves:
Ms.find "one" s2;; => 1
Ms.find "two" s2;; => 2
The map s2 is immutable but we can make a new map with three entries and bind s2 to that new map thus:
let s2 = Ms.add "three" 3 s2;;
Ms.find "three" s2;;
We print the whole map:
Ms.iter (fun s v -> print_string (s^"= "); print_int v) s2;;
which prints “one= 1three= 3two= 2”, sorted lexicographically by key.

A given map requires that members of its range be of the same type.

Ms.add "pi" 3.14159265
provokes:
Error: This expression has type int Ms.t = int Map.Make(String).t
but an expression was expected of type
float Ms.t = float Map.Make(String).t

The system has decided that s2 maps to integers only. However

Ms.add "pi" 3.14159265 Ms.empty;;
is a whole new function.

Maps are immutable; The redefinition of s2 is to a new map and the old map without the binding for “three” will be collected by the garbage collector. Actually much of the storage between the old and new maps is shared and only a little storage is free to be reclaimed.

We make a new module on using Ms which produces mutable maps, if that suits your fancy.


module C = Set.Make(Int32);;
let rec f j = if j = 0 then C.empty else C.add (Int32.of_int j) (f (j - 1));;
The above is not tail recursive but the equivalent following is:
let g j = let rec g s j = if j = 0 then s
  else g (C.add (Int32.of_int j) s) (j - 1) in g C.empty j;;