We can use pattern matching in named functions. See the
Sum.to function below, which sums up the numbers from 1 to
Unfortunately, the above implementation of
Sum.to will not work for negative numbers. In fact, if you try to run
Sum.to -1, we’ll be stuck in a loop.
We want to specify additional predicates regarding the value or type of the arguments that are passed into our function.
Sum.to, we want to make sure that
nis a strictly nonzero positive integer.
Time to use guard clauses:
We can have multiple guard clauses:
Note that the expressions you can use as guard clauses are limited. You can’t use your own functions as Elixir optimizes these clauses for performance reasons. A full list of available expressions are available here.