TL;DR
In the previous post, we introduced function overloading in Elixir, which is basically applied pattern matching to function input arguments. As pattern matching could not include logical operators, guards are mechanisms that extend function overloading with logical operators. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
As pattern matching in function arguments is powerful mechanics that make your code more concise and readable (remember to put overloaded functions next to each other!), we must reach for function guards when it comes to logical expressions.
As I think that Croatian VAT is too much for our poor economy, I would like to add an expensive country string if a country has a VAT greater than 20%.
As your Elixir experience will grow, you will become more ambitious. Let’s use functions in guard expression. As Elixir forces you to write clean and simple code, you will be surprised that it is impossible to use complex functions in guards. Guards documentation is to date place to check what is allowed.
Remember
- You reach for guards when you need an in-function argument pattern matching logical expressions.
- Elixir is not the type-safe language; you could easily end up comparing an atom with a number without any warning.
- In guards, you can use a limited set of functions.
- Elixir function overloading and guards help you to avoid complex, long, and nested if then else statements