O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required