[erlang-questions] is this a well written function
Bengt Kleberg
bengt.kleberg@REDACTED
Mon Feb 9 10:46:41 CET 2015
I like it.
It could be enhanced with a test that _input_ Number is higher _than_ 0 in:
% when the output is a number higher then 0 , the acc function will be
called.
sum(Number) -> sum_acc(Number, 0, 0 ).
bengt
On 02/09/2015 10:38 AM, Roelof Wobben 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 ?
>
> Roelof
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list