[erlang-questions] Side-effects in "if" guards

Edwin Fine <>
Thu May 15 23:42:17 CEST 2008

I saw something like this in some Erlang code. It is possible to achieve a
similar effect without using "if" as follows:

is_list(X) andalso string:to_lower(X) == X andalso length(X) == 5 and also
my:no_duplicates(X) andalso do_something(X).

do_something(X) ->
    %% Stuff...

Note the use of "==" instead of "=". Huge difference.

This is similar to Unix-ish shell-scripting techniques such as [[ -z "$NAME"
]] && echo "NAME not defined"


On Thu, May 15, 2008 at 2:10 PM, Darren New <> wrote:

> Being a newbie to Erlang, I wonder if there's a reason for the "if"
> statement to disallow side-effects in the guards, or whether it's just a
> result of using the same language construct for "if" as for "receive".
> I.e., I understand why guards in "receive" can't have side-effects, but
> the guards in "if" don't really seem to have that same problem.
> I often find myself often stumbling over that fact, needing to write a
> nested-three-deep "if" or auxiliary functions to do relatively simple
> (and side-effect-free operations) simply because the tests are too
> complex (calling my own code). For example, I can't say
>   if X is a list, and the list is length five,
>      and there are no duplicates -> good;
> I have to
>   if X is a list ->
>      Y = string:tolower(X),
>      if X = Y ->
>        if X is length five ->
>          V = my:no_duplicates(X),
>            if V -> good;
> Rather than the more straightforward
>   if X is a list andalso string:tolower(X) = X
>     andalso len(X) = 5 andalso true = my:noduplicates(X) -> good;
> Is there a reason for this other than not having to define (and
> implement) two different kinds of guards?
> Or am I doing something suboptimal in my programming by doing this, and
> there's really a clever but unobvious-to-me way of making this work better?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080515/ea83edba/attachment.html>

More information about the erlang-questions mailing list