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 Structured Data

Matching goes further—Elixir will look at the structure of the two sides when making a match:

 [ a, b, c ] = [1, 2, 3] ​#​ a = 1, b = 2, c = 3
 [ head | tail ] = [1, 2, 3] ​#​ head = 1, tail = [ 2, 3 ]

Once bound, a variable keeps the same value for the duration of the pattern match. So the following match will only succeed if the variable list is a three-element list where the first and last elements have the same value:

 [ a, b, a ] = list

You can mix constants and variables on the left-hand side. To illustrate this, I’m going to introduce a new Elixir data type, the tuple. A tuple is a fixed-length collection of values. We write tuple constants between braces:

 { 1, 2, ​"cat"​ }
 { :ok, result }

(The ...

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