[erlang-questions] is this a well written function
Roelof Wobben
r.wobben@REDACTED
Mon Feb 9 14:39:46 CET 2015
Masklinn schreef op 9-2-2015 om 10:51:
> On 2015-02-09, at 10:38 , Roelof Wobben <r.wobben@REDACTED> wrote:
>
>> Hello,
>>
>> I tried to solve the exercise where I have to calculate the outcome of 1 ... n
>>
>> So I have this :
>>
>> -module(sum_recursion).
>>
>> -export([sum/1]).
>>
>> % when the number is zero the outcome will also be zero
>> sum(0) ->
>> 0;
>>
>> % when the output is a number higher then 0 , the acc function will be called.
>> sum(Number) -> sum_acc(Number, 0, 0 ).
>>
>> % when the numbers are equal then the end is reached and the last item is added to the acc variable,
>> % the acc variable hold the value of the sum as it is calculated
>> sum_acc(Endnumber, Endnumber, Acc) ->
>> Acc + Endnumber ;
>>
>> % when the numbers are not equal then the end is not reached so the function is again called with the original number,
>> % the loop is increased by 1 and the acc function hold the value of the sum as it is calculated.
>> sum_acc(Endnumber, Number, Acc) ->
>> sum_acc(Endnumber, Number + 1, Acc + Number).
>>
>>
>> Now I wonder if this is well written Erlang ?
> I'd tend to write something like this instead:
>
> sum(End) -> sum_acc(0, 0, End).
>
> sum_acc(Acc, _, 0) ->
> Acc;
> sum_acc(Acc, Current, Rem) ->
> sum_acc(Acc + Current, Current + 1, Rem - 1).
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
Thanks both,
This is a version with a guard to take care that n is greater then 0
Masklinn,
I will study your version to see how you see when it's is the end.
Roelof
More information about the erlang-questions
mailing list