[erlang-questions] is this a well written function
Mon Feb 9 10:51:19 CET 2015
On 2015-02-09, at 10:38 , Roelof Wobben <r.wobben@REDACTED> wrote:
> I tried to solve the exercise where I have to calculate the outcome of 1 ... n
> So I have this :
> % when the number is zero the outcome will also be zero
> sum(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) ->
sum_acc(Acc, Current, Rem) ->
sum_acc(Acc + Current, Current + 1, Rem - 1).
More information about the erlang-questions