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.

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.

Related articles

Leave feedback...

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.