ðĶPattern matching
The =
operator is known as the match operator in Elixir. This is because the implicit behavior of =
is to perform a match between the left hand side and right hand side of the equation. This is on top of the existing assignment behavior. As a result, the following code can be interpreted as:
As a result, =
can be used to de-structure a variable into its "parts" as it will map all matched LHS values to the found values on the RHS. This is also known as pattern matching.
Tuples
For instance, you can de-structure the contents of a tuple:
Notice how each value of the tuple x
is directly matched to a variable on the LHS. Additionally, if you attempt to de-structure/pattern match a variable with mismatched "parts", you will receive an error:
Lists
You can also perform pattern matching on lists. However, since lists are of variable length (compared to tuples), you may not know the exact number of elements in a list when pattern matching, so you can use the |
operator instead:
The |
operator works like the hd/1
and tl/1
function in one.
You can optionally "ignore" a variable in pattern matching by replacing it with _
so the part will still be matched but not assigned to any variable or compared against anything:
Maps
As mentioned in Keyword lists and maps, while keyword lists support pattern matching, their order dependent nature makes it hard to use with pattern matching. However, maps are the perfect candidate for pattern matching against "dynamic" structures:
Deeply nested structures
Pattern matching also applies to any nested structures as long as you know its "parts" ahead of time:
Last updated