Pattern Matching and Functions

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 ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.