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