[erlang-questions] The If expression

Richard O'Keefe ok@REDACTED
Mon Jan 26 04:50:13 CET 2009


On 24 Jan 2009, at 11:35 am, Fredrik Svahn wrote:
>> - 'if' isn't actually all that rare.  In some code I wrote last
>> year, I find one 'if' for every four 'case's.  The OTP sources
>> have 1 if/10 case, which is less common, but not _that_ rare.
>> If the old sense of 'if' were rare, we could probably live with
>> the confusion.
>
> Newcomers to this mailing list asking how to use "if" are invariably
> recommended to use "case" instead. Combined with the fact that you can
> only use guards it is almost FAQ material. Considering this and all
> the beating the 'if' expression has gotten over the years on the
> mailing list my assumption was that the use of 'if' was really rather
> infrequent even outside of OTP. I might be wrong.
>
> (Hmmm, I just checked, and there actually is a chapter about 'if':s in
> the FAQ. It is recommending the use of 'case' and even states that
> "case is used much more frequently").

Ten to one *is* "much more frequently".
However, one in ten is not a negligible proportion.

> Just out of curiosity, is there any other programming language out
> there which has an 'if' and which does not have an 'else' apart from
> the Commodore 64 BASIC? I am not saying Erlang should have because
> everyone else does. I am just wondering out of curiosity.

Dijkstra's notation, Promela, classic Lisp (to this day, if you want
an "else" in a COND, you have to use the equivalent of "; true ->"),
Occam.

- As a result the new syntax is rather inconvenient.  The majority
>
>>  of my existing uses of 'if' have more than one arm, so would need
>>  nested new-'if's.  It's hard to see that as an improvement.
>
> The proposal is backwards compatible (with the obvious exception that
> 'else' would need to become a keyword) so there is no need for you to
> change your coding style.

That much was obvious.  My point is that common things like
	if X < Y -> a()
	 ; X > Y -> b()
	 ; X ==Y -> c()
	end
have to be rewritten as
	if X < Y -> a()
	else
	   if Y > Y -> b()
	   else
	      c()
	   end
	end
so there isn't much *point* in changing coding style either.
>
> There is a lot of code out there to critically review, then.

Yes, there is.  In fact, looking for 'true' and 'false' is a good
way to find code that could be clearer.

> In fact
> 'true' is the second most popular atom in the OTP code, and 'false' is
> the fourth most popular.

No dispute there.  Oh, that it were not so!
>
> What else can it really be used for? Ok, there are a couple of guard
> bifs, but that is basically it, isn't it?

Type tests.



More information about the erlang-questions mailing list