May 2018
Intermediate to advanced
412 pages
9h 3m
English
Let’s get more ambitious. Let’s write a function that takes a list of numbers and returns a new list containing the square of each. We don’t show it, but these definitions are also inside the MyList module.
| | def square([]), do: [] |
| | def square([ head | tail ]), do: [ head*head | square(tail) ] |
There’s a lot going on here. First, look at the parameter patterns for the two definitions of square. The first matches an empty list and the second matches all other lists.
Second, look at the body of the second definition:
| | def square([ head | tail ]), do: [ head*head | square(tail) ] |
When we match a nonempty list, we return a new list whose head is the square of the original list’s head ...
Read now
Unlock full access