October 2014
Intermediate to advanced
280 pages
7h 20m
English
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 ...
Read now
Unlock full access