Erlang Notes – Gaurds and gaurd sequences

Here is the seventh of some notes about erlang.
Obviously this is a very cursory glance at things. It’s really just notes to help me remember things. If you’re looking for something in more detail you can take a look at the erlang reference manual.

Guards

As far as I understand, guards provide an enhancement to pattern matching, allowing us to enhance our pattern matching abilities by testing the values of variables. I’m not quite sure exactly where guards can be used: No limitations on where are mentioned yet, so I’m going to assume that you can use them anywhere you are using pattern matching, although it seems a bit odd to use them on the RHS of an expression.

The simplest example of a guard is probably something like:


sqrt(X) when X < 0 -> exit(dumbValue).

In this case when we call sqrt with a value less than 0 we’ll exit. Pretty straight forward.

Guard sequences

We can also combine guard clauses to give us more complex checks:


sqrt(X) when X < 0, X < 20 -> exit(notInValue).

Guard sequences are simply separate guard clauses conjoined in some way. They typical way they are conjoined is simply by a comma as above, in which case the comma represents an ‘and’ statement. They can also be combined by short-circuit boolean operators andalso or orelse, or by the normal boolean operators or or and.

These cases function much as you would expect, with short-circuit boolean expressions functioning as in other languages.

Leave a Comment