May 2018
Intermediate to advanced
412 pages
9h 3m
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.
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 ...
Read now
Unlock full access