Variables In Elixir Pattern Matching — Tentamen Software Testing Blog

Variable Pattern Matching In Elixir


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 and tuples that are the result of 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. Ignores the date part of local time.


The next line from the screenshot shows that it is possible to use nesting on the pattern side. With tuple nesting, we extracted current 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 .


  • pattern matching recap
  • variable bounding
  • anonymous variable
  • dynamic pattern matching

Originally published at on January 1, 2021.

Founder of Tentamen, software testing agency.