[erlang-questions] is this a well written function

Roelof Wobben r.wobben@REDACTED
Mon Feb 9 16:27:11 CET 2015


Fred Hebert schreef op 9-2-2015 om 16:18:
> On 02/09, Roelof Wobben wrote:
>> A new try after some remarks :
>>
>> % When End is equal to zero all the numbers are added
>> sum_acc(Acc, 0) ->
>>       Acc;
> The only criticism I'd have is that usually, Erlang programmers will put
> the accumulator last in the list of arguments, and the variable you
> iterate on in first positions.
>
> So the function clause above would be
>
>      sum_acc(0, Acc) ->
>          Acc;
>
> Regards,
> Fred.
>

Thanks,

Changed it like this :

-module(sum_recursion).

-export([sum/1]).

% when the number is zero the outcome will also be zero
sum(0) ->
   0;

% when a number is greater then 0 , call the helper function.
sum(End) when End > 0 ->
   sum_acc(End,0).

% When End is equal to zero all the numbers are added
sum_acc(0,Acc) ->
      Acc;

% when end is not zero there are more numbers to be added.
sum_acc(End, Acc) ->
      sum_acc(End - 1, Acc + End).

Roelof




More information about the erlang-questions mailing list