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.

ABS(X) = { X < 0: -1 times X, X >= 0: X }

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.

written by
Craig
published
2008-09-10
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO http://barkingiguana.com/2008/09/10/adventures-in-erlang-predicate-guards.html.orig
curl -LO http://barkingiguana.com/2008/09/10/adventures-in-erlang-predicate-guards.html.orig.asc
gpg --verify adventures-in-erlang-predicate-guards.html.orig{.asc,}