Variables In Elixir Pattern Matching — Tentamen Software Testing Blog

Variable Pattern Matching In Elixir

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.

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

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store