You can also pattern match on Elixir Data Structures such as Lists.
Lists
Matching on a list is quite simple.
[head | tail] = [1,2,3,4,5] # head == 1 # tail == [2,3,4,5]
This works by matching the first (or more) elements in the list to the left hand side of the |
(pipe) and the rest of the list to the right hand side variable of the |
.
We can also match on specific values of a list:
[1,2 | tail] = [1,2,3,4,5] # tail = [3,4,5] [4 | tail] = [1,2,3,4,5] ** (MatchError) no match of right hand side value: [1, 2, 3, 4, 5]
Binding multiple consecutive values on the left of the |
is also allowed:
[a, b | tail] = [1,2,3,4,5]
# a == 1
# b == 2
# tail = [3,4,5]
Even more complex - we can match on a specific value, and match that against a variable:
iex(11)> [a = 1 | tail] = [1,2,3,4,5] # a == 1