[erlang-questions] Side-effects in "if" guards
Igor Ribeiro Sucupira
Sun May 18 04:06:19 CEST 2008
On Thu, May 15, 2008 at 3: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?
In your example, I would use a case (in fact, I very rarely use ifs):
case is_list(X) andalso string:tolower(X) =:= X andalso length(X) == 5
andalso my:noduplicates(X) of
true -> good;
false -> bad.
> 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."
> erlang-questions mailing list
More information about the erlang-questions