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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.