July 2017
Intermediate to advanced
284 pages
6h 45m
English
Our MyList.sum example shows that pattern matching also applies to calling functions. Do you see that? The function parameters act as the left-hand side of the match, and the arguments you pass act as the right-hand side.
Here is another (hoary old) example: it calculates the value of the nth Fibonacci number.
Let’s start with the specification of Fibonacci numbers:
| | fib(0) -> 1 |
| | fib(1) -> 1 |
| | fib(n) -> fib(n-2) + fib(n-1) |
Using pattern matching, we can turn this specification into executable code with minimal effort:
| | defmodule Demo do |
| | |
| | def fib(0), do: 1 |
| | def fib(1), do: 1 |
| | def fib(n), do: fib(n-2) + fib(n-1) |
| | |
| | end |
Elixir comes with an interactive shell called iex. This ...
Read now
Unlock full access