[erlang-questions] If Condition vs. Multiple Function Clauses
Steve Davis
steven.charles.davis@REDACTED
Sat Jun 15 02:40:06 CEST 2013
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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130614/83f355fb/attachment.htm>
More information about the erlang-questions
mailing list