Expanding Control with Guard Clauses

Creating multiple functions with pattern matching to control the program flow can be exhausting sometimes. In the example where we created the NumberCompare module, we have to build auxiliary functions to handle the >= operation result. Creating too many functions for trivial tasks can generate code that is hard to maintain. We can improve this using Elixir guard clauses. Guard clauses permit us to add Boolean expressions in our functions, adding more power to our function clauses.

We can create guard clauses by using the when keyword after functions’ parameters. Let’s see how it works for improving our NumberCompare code:

 defmodule​ NumberCompare ​

Get Learn Functional Programming with Elixir now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.