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

Steve Davis <>
Sat Jun 15 15:30:10 CEST 2013


Yep, that would be a better, more consistent way to go...

if  M == N -> a();
    M > N -> b();
    _ -> c()
end.

:-) ty Erik

/s

On Jun 15, 2013, at 2:42 AM, Erik Søe Sørensen <> wrote:

> Me too. One might even consider using "_" for such a catch-all.
> (A reason in favour of that, apart from the syntactic similarity with "case"-catch-alls: 'else' is a valid expression like 'true', '_' isn't and therefore doesn't confuse by the apparent overlap.)
> 
> Den 15/06/2013 02.40 skrev "Steve Davis" <>:
> I strongly (personally) dislike use of "if" syntax, but only because of the counterintuitive "true" evaluation.
> 
> What if the language were to return the atom "else" instead of "true"?
> 
> I doubt that would be considered "better" but it would sure make things more readable...
> 
> /s
> 
> On Friday, June 14, 2013 8:06:33 AM UTC-5, Lars Herbach wrote:
> Hi List,
> I'm currently working myself through the "Études for Erlang" book [1] and in exercise it wks's to write a recursive function, calculating the greatest common divisor for two numbers N and M. The suggested solution is a single gcd/2 function with an If condition and recursion:
> 
> gcd(M, N) -> 
>     if M == N -> M;
>        M > N -> gcd(M - N, N;
>        true -> gcd(M, N - M)
>     end.
> 
> 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?
> 2) Are there any benefits in regards of efficiancy for the first solution?
> 
> Thanks,
> Lars.
> 
> 
> [1]: http://shop.oreilly.com/product/0636920030034.do
> 
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130615/351ab1a0/attachment.html>


More information about the erlang-questions mailing list