Using Head and Tail to Build a List

Let’s get more ambitious. Let’s write a function that takes a list of numbers and returns a new list containing the square of each. We don’t show it, but these definitions are also inside the MyList module.

lists/mylist1.exs
 
def​ square([]), ​do​: []
 
def​ square([ head | tail ]), ​do​: [ head*head | square(tail) ]

There’s a lot going on here. First, look at the parameter patterns for the two definitions of square. The first matches an empty list and the second matches all other lists.

Second, look at the body of the second definition:

 
def​ square([ head | tail ]), ​do​: [ head*head | square(tail) ]

When we match a nonempty list, we return a new list whose head is the square of the original list’s head ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.