[erlang-questions] is this a well written function
Masklinn
masklinn@REDACTED
Mon Feb 9 10:51:19 CET 2015
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).
More information about the erlang-questions
mailing list