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 the list-length algorithm in Elixir is easy:

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

Get Programming Elixir ≥ 1.6 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.