Exception
Exception

Reputation: 8379

Where I am wrong in this module code

I have created a module with the below code

 -module('calc') .
 -export([sum/2]) . (0)

 sum(L) -> sum(L,0);   (1)
 sum([],N) -> N;   (2)
 sum([H|T], N) -> sum(T, H + N) (3) .

and in shell, when I compile it is returning me error like below

 calc.erl:5: head mismatch
 calc.erl:2: function sum/2 undefined
 error

As per my understanding from the book, 1 clause will receive the list and will pass it to the (3). Then (3) will return the desired result.
But I don't know where I have committed the mistake. Please help me on this.

And please help me to understand what is /2 in export statement.

Upvotes: 1

Views: 172

Answers (2)

Artefact2
Artefact2

Reputation: 7634

You have a syntax error at line (1). The functions sum/1 and sum/2 are different, so your code should look like:

sum(L) -> sum(L,0). %% notice the . instead of ;

sum([],N) -> N;
sum([H|T], N) -> sum(T, H + N).

The /2 is the arity of your function, that is, the number of arguments it takes. So, in your case, the function you want to export is sum/1.

Upvotes: 7

Sankar V
Sankar V

Reputation: 4862

Check this link

Write a function that calculate the sum of integers in a list in Erlang

/2 in export statement indicates the number of arguments to the function sum.

Upvotes: 0

Related Questions