How To Do Control Flow In Elixir With Pattern Matching Operator — Tentamen Software Testing Blog

TL;DR

In the previous post, we presented four ways how to do control flow in Elixir. Today we explain Elixir Pattern Matching Operator. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Control Flow

At first, it could be strange to comprehend that Elixir Pattern Matching is meant to do program control flow. The biggest benefit of pattern matching control flow is less boilerplate code. To master Elixir pattern matching, you need to learn:

  • The Match Operator
  • Matching Tuples
  • Matching Constants
  • Variables In Patterns
  • Matching Lists
  • Matching Maps
  • Matching bitstrings and binaries
  • Compound Match
  • General Behaviour

Let’s start with the match operator.

The Match Operator

Elixir language is a strange beast. For example, there is no assignment operation, but instead, we do pattern matching. What is happening in the above screenshot?

In the first line, variable a is pattern matched to 1. When we use match operator =The left side is pattern , and the right side is expression that evaluates to Elixir term. In terms of other languages, variable a is bound to value 1.

In the second line, we do pattern matching. 1 is a pattern and a is Elixir expression that evaluates to 1. We have a pattern match!

In the third line, we have pattern matching failure that is reported with MatchError exception. Why? 2 is on the left side, so it represents pattern. a is on the right side, and it is an Elixir expression that evaluates to 1. We do not have a match.

Do you see how we actually do with pattern matching a control flow? Very exciting. Of course, for flow control, we need more code. Stay tuned.

Remember

  • = is not an assignment but pattern matching operator
  • you will see a lot of MatchError in application logs that indicates an error in that program

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

--

--

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
Karlo Smid

Karlo Smid

Founder of Tentamen, software testing agency.