[erlang-questions] is this a well written function

Roelof Wobben r.wobben@REDACTED
Mon Feb 9 15:11:20 CET 2015


Roelof Wobben schreef op 9-2-2015 om 14:39:
> 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). 


A new try after some remarks :

-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(0, End).

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

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

Roelof



More information about the erlang-questions mailing list