[erlang-questions] If Condition vs. Multiple Function Clauses

ok <>
Sat Jun 15 14:33:16 CEST 2013

> I strongly (personally) dislike use of "if" syntax, but only because of
> the
> counterintuitive "true" evaluation.

What's counterintuitive about it?  It's instantly familiar
to any Lisp programmer (except for being spelled 'true' instead
of 'T') or to any Prolog programmer.
> What if the language were to return the atom "else" instead of "true"?

Now that _would_ be unintuitive.  In any case, 'if' has no truck
with values of any kind, it is driven by guards that succeed or
fail, not by expressions that have values.

>>  gcd(M, N) ->
>>     if M == N -> M;
>>        M > N -> gcd(M - N, N;
>>        true -> gcd(M, N - M)
>>     end.

That is indeed a common Erlang style, but in a language
that uses both commas and semicolons so heavily, and
especially in a language that is lacking an 'elif' or 'else'
keyword, I find it advisible to put semicolons in a place
where commas never go, namely at the beginning of lines.
It is also easier to read if the arrows are aligned.

    gcd(M, N) ->
        if M > N -> gcd(M - N, N)
         ; N < M -> gcd(M, N - M)
         ; true  -> M

>>  I by myself took another way, working with multiple function clauses
>> (did I name it right?):
>>  gcd(M, N) when M == N ->
>>     M;
>> gcd(M, N) when M > N ->
>>     gcd(M - N, N);
>> gcd(M, N) ->
>>     gcd(M,  N - M).
>>  Now I've got two questions about that:
>> 1) Is my solution still recursive, since I practically call different
>> functions?

Yes your solution is still recursive.
In all essentials, it is the *same* solution.
No, you are *NOT* calling different functions.
There is only one gcd/2 function, and you are
calling *it* (not *them*).
In fact you *can't* call a clause.

>> 2) Are there any benefits in regards of efficiency for the first
>> solution?

If you really want to know, measure them.
But it would not be surprising if the compiler
generated essentially the same code.
Anyone who cared about efficiency that much would
be using a M rem N rather than M - N, or would be
using a binary gcd.

First you write something that is obviously
correct.  Then you test it and fix the mistakes.
Then you can measure it, and consider a rewrite
if it is too slow.

More information about the erlang-questions mailing list