# [erlang-questions] is this a well written function

Richard A. O'Keefe ok@REDACTED
Wed Feb 11 05:26:47 CET 2015

```On 9/02/2015, at 10:38 pm, Roelof Wobben <r.wobben@REDACTED> wrote:

> Hello,
>
> I tried to solve the exercise where I have to calculate the outcome of 1 ... n

The outcome of doing what?

So I have this :
>
> -module(sum_recursion).

This is a poor name.  From the outside, you cannot tell how the sum is
computed, and you probably should not care.  If you are doing exercises
from a book, it is better to name your modules for the exercises,
e.g. chapter_2_exercise_4.
>
> -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 ).

(1) true
(2) useful.

Ad (1), there is no 'acc' function, so the comment is untrue.
Ad (2), the comment is not USEFUL.

What you are missing is a comment that says WHAT THE FUNCTION IS ABOUT.
Something like

%%  sum(N) answers 1+2+...+N when N is a non-negative integer.
%%  It is not defined for other arguments.
%%  The implementation uses tail recursion, where the
%%  control argument counts up from 0 to N and the
%%  accumulator argument holds the running prefix of the sum.

These observations on comments have nothing to do with Erlang.
should be true, useful, and not just paraphrase the code.

>
> % 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

This comment is not good.  You have *three* numbers.  Which two of them are supposed to be
equal?  The phrase "junk comment" is generally used for comments that simply paraphrase the
code.

In Erlang, you CANNOT "add to the acc variable" (which is Acc, not acc).
Once an Erlang variable has a value, that is its value for as long as it exists.

Good code for this might be

sum(N) when is_integer(N), N >= 0 ->
(N * (N+1)) // 2.

```