Adventures In Erlang: predicate guards
Sometimes a function behaves differently based on it's inputs. Consider, for example, calculating the absolute value of a number. If the number is less than 0 then the result is -1 * INPUT. If the number is greater than or equal to zero then the number is the same as the input.

This can be accomplished in Erlang using predicate guards: conditions on the inputs which are defined just after the argument list of a predicate.
-module(maths).
-export([abs/1]).
abs(X) when X < 0 -> -1 * X;
abs(X) -> X.
Of course Erlang does already provide a math module which exports abs. This is just a simple example of how to implement guards. It's also the reason that my module is called maths instead of math. Ick.
Related articles
Leave feedback...
Commenting is closed for this article.
