O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required