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

Darren New <>
Thu May 15 20:10:51 CEST 2008


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?

-- 
   Darren New / San Diego, CA, USA (PST)
     "That's pretty. Where's that?"
          "It's the Age of Channelwood."
     "We should go there on vacation some time."



More information about the erlang-questions mailing list