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 Process a List

Now we can split a list into its head and its tail, and we can construct a list from a value and a list, which become the head and tail of that new list.

So why talk about lists after we talk about modules and functions? Because lists and recursive functions go together like fish and chips. Let’s look at finding the length of a list.

  • The length of an empty list is 0.

  • The length of a list is 1 plus the length of that list’s tail.

Writing that in Elixir is easy:

lists/mylist.exs
 
defmodule​ MyList ​do
 
def​ len([]), ​do​: 0
 
def​ len([head|tail]), ​do​: 1 + len(tail)
 
end

The only tricky part is the definition of the function’s second variant:

 
def​ len([ head | tail ]) ...

This is a pattern match ...

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