Creating a Map Function

Learn about the map function in Elixir.

We'll cover the following

In the previous lessons, we described the square and len() functions. All the work is done in the second function definition, and that definition looks about the same for each:

  • It returns a new list whose head is the result of either squaring or incrementing the head of its argument.
  • The tail is the result of calling itself recursively on the tail of the argument.

The map function

Let’s generalize this. We’ll define a function called map that takes a list and a function as a parameter. It applies that function to each element in the original and returns the new list.

Run the MyList.map [1,2,3,4], fn (n) -> n*n end command to run the code below.

Get hands-on with 1200+ tech skills courses.