21 Standard Library Map

The Standard Library's Map module is a great example of functors! It implements a Tree Map (a map backed by balanced binary trees). The Map module has a functor in it called make. It makes a Map data structure based on a Map.OrderedType module.

You must pass in module that has two things, a type, t, for the keys, and a comparison function, compare, for the keys.

(The Map module needs a comparison function for the balanced binary tree implementation)

The output of the functor is of type S, which contains all the typical map structures. Let's create a map for days of the week!

First, we'll need a type.

We'll also probably want to map a day to an integer:

Now let's create a map whose keys are days. We need to create a module for this:

Now we can write a map to map days to whatever else we want!

DayMap must now have keys that are days. Let's map them to their long names (strings):

Note that m is abstract, but we can use the functions that DayMap provides to examine our tree. It's easiest to do that if we just open DayMap here:

Let's check if monday is a key in the map!

Let's find the value of Tuesday!