[erlang-questions] If Condition vs. Multiple Function Clauses
Lars Herbach
lars@REDACTED
Fri Jun 14 15:06:33 CEST 2013
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/417b9646/attachment.htm>
More information about the erlang-questions
mailing list