More Complex Matches

First, a little background syntax. Elixir lists can be created using square brackets containing a comma-separated set of values. Here are some lists:

 
[ ​"Humperdinck"​, ​"Buttercup"​, ​"Fezzik"​ ]
 
[ ​"milk"​, ​"butter"​, [ ​"iocane"​, 12 ] ]

Back to the match operator.

 
iex>​ list = [ 1, 2, 3 ]
 
[1, 2, 3]

To make the match true, Elixir bound the variable list to the list [1, 2, 3].

But let’s try something else:

 
iex>​ list = [1, 2, 3]
 
[1, 2, 3]​​
 
iex>​ [a, b, c ] = list
 
[1, 2, 3]​​
 
iex>​ a
 
1​​
 
iex>​ b
 
2​​
 
iex>​ c
 
3

Elixir looks for a way to make the value of the left side the same as on the right. The left side is a list containing three variables, and the right is a list of three values, so the two sides ...

Get Programming Elixir 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.