Macro Guard Clauses in Elixir
Have you ever wanted to pass your own custom function into a guard clause?
Lets start by looking at a super basic guard clause here:
Let's say we want to get more specific with the operation inside of the when
guard. This is overkill for our situation, but lets say we want the when
to use a custom function of ours instead of a basic operation, but when
guards don't allow you to directly pass functions to them.
Elixir has a fancy macro called defguard
that allows you to define custom guards like functions. Let's change our function up and define a guard that checks if our argument is both a integer and even.
Let's use that guard in our function
Even though this example is a bit overkill, the option to use custom guards is a cool elixir feature.
Tweet