[erlang-questions] is this a well written function

Roelof Wobben r.wobben@REDACTED
Mon Feb 9 15:38:10 CET 2015


I know , the exercise is stated this :

Write a function sum/1which, given a positive integer N, will return the 
sum of all the
integers between 1 and N.

Roelof


Martin Koroudjiev schreef op 9-2-2015 om 15:32:
> It's perfect, just note that you will get "no function clause" exception
> if you pass negative number to the function which is probably desired
> result.
>
> Martin
>
> On 2/9/2015 4:11 PM, Roelof Wobben wrote:
>> 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
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>




More information about the erlang-questions mailing list