In the previous post, we presented the pattern matching operator. Today we explain Elixir tuples Pattern Matching. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
In the previous post, we learn that
= is a pattern matching operator. Let’s pattern match on tuples. We know that usually, the usage of tuples is to return values from functions. In above screenshot, we first pattern matched tuple with variables
name to two value tuple. We have a pattern match that results inbounding
role to :tester and
Then we have an example of a pattern match
MatchError. We used the wrong pattern on the left side of the pattern match,
name binary does not match to
Karlo Šmid binary.
Integer.parse the function takes as input
binary and tries to transform it to an integer. On successful parsing, it returns a tuple with two values, resulting in integer and remaining value, if input binary represents a
We have a
MatchError because we try to match three value tuple with two value tuple.
- we use tuples as function return values
- pattern match tuples with same number of values
- learn to read