[erlang-questions] If Condition vs. Multiple Function Clauses
J David Eisenberg
Sat Jun 15 16:18:13 CEST 2013
> Message: 8
> Date: Fri, 14 Jun 2013 13:06:33 +0000
> From: Lars Herbach <lars@REDACTED>
> To: "erlang-questions@REDACTED" <erlang-questions@REDACTED>
> Subject: [erlang-questions] If Condition vs. Multiple Function Clauses
> Message-ID: <EF118D9F-6346-4CDB-942F-30A29CBD840C@REDACTED>
> Content-Type: text/plain; charset="iso-8859-1"
> Hi List,
> I'm currently working myself through the "?tudes for Erlang" book  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)
> I by myself took another way, working with multiple function clauses (did I name it right?):
> gcd(M, N) when M == N ->
> gcd(M, N) when M > N ->
> gcd(M - N, N);
> gcd(M, N) ->
> gcd(M, N - M).
You're right. Your solution is much more in the spirit of Erlang. I
wrote the étude with "if" because I wanted to have an example of its
use somewhere in the book. I will update the book to put in your
solution as an alternate answer, with some words about using guards in
preference to "if"..
> 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?
> : http://shop.oreilly.com/product/0636920030034.do
More information about the erlang-questions