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:
defmodule MyList do
def len(), do: 0
def len([head|tail]), do: 1 + len(tail)
The only tricky part is the definition of the function’s second variant:
def len([ head | tail ]) ...
This is a pattern match ...