TL;DR
In the previous post, we presented the Elixir constants Pattern Matching. Today we move onto Variables In Elixir 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.
Pattern Matching Recap
Let’s recap Elixir pattern-matching. Pattern matching operator is =
. At first, this seems odd because, in OO languages, this is the assignment operator. On the left side of it, we have a pattern, and on the right side, we have an Elixir term.
Variables In Elixir Pattern Matching
What happens when we have a variable on the pattern side? Variable is bound to matched value on the right side, where we have an Elixir term. In the above screenshot, we bounded current date
and time
tuples that are the result of :calendar.local_time()
function.
Anonymous Variables
Sometimes we want to bound just parts of the Elixir term from the right side. In that case, we use an anonymous variable, _
. We designate on the pattern side which part we want to ignore from pattern matching (and bounding) with the anonymous variable. Screenshot example would successfully match for any day.
To make code mode readable, it is good practice to give a name for the anonymous variable, so we know which part of the pattern we ignore. _date
Ignores the date part of local time.
Nesting
The next line from the screenshot shows that it is possible to use nesting on the pattern side. With tuple nesting, we extracted current hour
value.
Dynamic Patterns
It is also possible to create a dynamic pattern matching with existing variables. In the pattern, we denote the existing pattern value with ^
.
Remember
- pattern matching recap
- variable bounding
- anonymous variable
- dynamic pattern matching
Comments are closed.