Map creates a "mapping". For instance, lets say I have some data that is users and passwords. Since each user has a password, I could use the Map module to create a mapping from user names to their passwords. The Map module does this efficiently in a functional way. In the example below I am going to do a mapping from strings to strings. However it is possible to do mappings with all different types of data.
To create a Map I can do
module MyUsers = Map.Make(String);;
Ok we have created the module now lets start putting something into it. Where do we start? Well lets try an empty map to begin with
let m = MyUsers.empty;;
Hummm. An empty map is kind of boring so lets add some data
let m = MyUsers.add "fred" "sugarplums" m;;
We have now added "fred" and his password of "sugarplums" to our map. There is a fairly important point to make here. Half of the type of m was fixed when we created it. Since we created MyUsers using the String module, we have to map from strings to any type. Once we add fred with his password, we fix the rest of m's type, as his password is a string. If we want a map from strings to integers or a map from integers to whatever we will have to create another map - m can now only associate strings to strings. If we want a map from something other than strings, we'll have to use Map.Make to make a new module with functions for that type.
Lets add in some additional data just for kicks. Note that each time we add an association to m, we rebind m. This is because Map is functional, and the original m is not mutated by each addition.
let m = MyUsers.add "tom" "ilovelucy" m;; let m = MyUsers.add "mark" "ocamlrules" m;; let m = MyUsers.add "pete" "linux" m;;
Now that we have some data inside are Map module wouldn't it be nice to be able to view that data at some point? Lets begin by creating a simple print function.
let print_users key password = print_string(key ^ " " ^ password ^ "\n");;
We have here a function that will take two strings, a key and a pasword and print them out nicely including a new line character at the end. All we need to do is have this function applied to are mapping. Here is what that would look like.
MyUsers.iter print_users m;;
The reason we put are data into a mapping however is probably so we can quickly find the data. Lets actually show how to do a find.
MyUsers.find "fred" m;;
This should quickly and efficienty return Fred's password of "sugarplums".