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

Constant Pattern Matching In Elixir

TL;DR

In the previous post, we presented how to pattern-match tuples. Today we move on to Elixir constants 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.

Constants

Let’s recall how to generally do pattern matching in Elixir. We have left and right sides where the left side is called a pattern, and the right side is Elixir expression (term).

First, two lines in the above screenshot iex session show constant pattern matching with no practical value. We successfully match the right side term that evaluates to 1 to left side pattern 1.

The second line shows an unsuccessful match with MatchError, right side term 2 could not be matched to left side pattern 1.

Constant Pattern Matching Idiom

So what is the purpose of pattern matching constants? Functions that follow Elixir error handling idiom, return as part of result tuple one constant value. That constant is usually an atom.

In the above screenshot, you can see an example of pattern matching tuple and constant with the function’s result. In a happy path, we expect :ok atom and file content. File.read Returns in case of error tuple with two atoms. The first indicates an error state, and the second one gives us an error reason. In our case, :enoent is Erlang atom for file not found.

Remember

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