17 Implementing Map

Lets look at how map could be written by looking at how some other functions can be applied to manipulate lists.

Let's add one to every element in a list:

Now let's test our function:

Perfect!

What if we wanted to concatenate 3110 to each item in a list

Look at the implementation of these two functions. There's a lot repeated code, let's factor it out:

let rec transform = function
    | [] -> []
    | h :: t -> ?? :: transform t

What do we do with the ??? Let's pass a function to transform the element

Now we can implement our add1 and concat3110 functions with transform

Look at that!

Guess what. Transform is actually map! This is the implementation of List.map in the standard library:

source

let rec map f = function
    [] -> []
  | a::l -> let r = f a in r :: map f l

Let's look at the type of map:

It takes a function of type ('a -> 'b), because you don't need to return a list of the same type!

Map takes that function, and an 'a list, and applies the function to each of them, then returns a 'b list.

What we just did here was apply the abstraction principle: Factor out recurring code patterns. Don't duplicate them.