How To Pattern Match Tuples In Elixir — Tentamen Software Testing Blog

Karlo Smid
2 min readDec 19, 2020

--

Elixir Tuple Matching

TL;DR

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.

Tuples

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 role and name to two value tuple. We have a pattern match that results inbounding role to :tester and name to karlo.

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 float value.

We have a MatchError because we try to match three value tuple with two value tuple.

Remember

  • we use tuples as function return values
  • pattern match tuples with the same number of values
  • learn to read MatchError message.

Originally published at https://blog.tentamen.eu on December 19, 2020.

--

--

Karlo Smid
Karlo Smid

Written by Karlo Smid

Founder of Tentamen, software testing agency.

No responses yet