Adventures in Erlang: Predicate Guards

September 10, 2008 · 1 min read

Sometimes a function needs to behave differently depending on its inputs. Consider calculating the absolute value of a number: if the number is less than zero, you multiply by -1; if it's zero or greater, you return it unchanged.
ABS(X) = { X < 0: -1 times X, X >= 0: X }
In Erlang, you handle this with predicate guards -- conditions on the inputs defined right after the argument list: ```erlang -module(maths). -export([abs/1]). abs(X) when X < 0 -> -1 * X; abs(X) -> X. ``` The `when X < 0` part is the guard. If it evaluates to true, that clause matches. Otherwise, Erlang falls through to the next clause -- which in this case has no guard and matches everything. Erlang already provides a built-in `abs` function in its `math` module, of course. This is just a simple illustration of how guards work -- and the reason my module is called `maths` instead of `math`. Naming collisions: the eternal struggle.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.