Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10867

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

As I'm learning Erlang just by reading books and doing my own exercises (NOT for homework), I'm struggling with even the most simple task that I mentioned in the title.

Here's what I've done:

I created a file called sum.erl with the following lines of code:

-module(mysum).
-export([mysum/1]).

mysum(L) -> 
   mysum(L, 0).

mysum([H|T], acc) -> 
   mysum(T, H + acc); 

mysum([], acc) ->
   acc.

Then I compile:

erl sum.erl

which takes me to a shell. There, I typed:

1> L = [1, 3, 7].
[1, 3, 7]
2> mysum(L).
** exception error: undefined shell command mysum/1
3>sum:mysum(L).
** exception error: undefined function sum:mysum/1

Say what ? Why am I getting those errors and even though the error messages are just slightly different, I'm thinking maybe their meanings are far apart?

UPDATE: New code

-module(sum).
-export([sum/1]).

sum(L) -> 
   sum(L, 0).

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

sum([], Acc) ->
   Acc.

Then

1>L = [1,2,3].
[1,2,3]
2>sum:sum(L).
** exception error: no function clause matching sum:sum([1,2,3],0)

Upvotes: 2

Views: 5864

Answers (2)

Adam Lindberg
Adam Lindberg

Reputation: 16587

The file should be called mysum.erl, the same as the name in the -module directive. Anything else is a compiler error in Erlang.

Make sure that you have compiled it using c(mysum) in the shell (and you're in the directory that mysum.erl is in.

Since your module is named mysum and the exported function is named mysum, thus you should call it with:

3> mysum:mysum(L)

Also, the variable that you store the results in, acc, should be named Acc (capital a). Otherwise, it's an atom and you will get a function_clause error as soon as you call mysum(L, 0) because no clause handles 0 as a second argument (0 merely compared to the atom acc).

Upvotes: 9

Dan Cecile
Dan Cecile

Reputation: 2493

Your new code seems to work. Try recompiling:

1> c(sum).
{ok,sum}    
2> sum:sum([1, 2, 3]).
6

The erl command will load any existing .beam files; an explicit compilation is required to reload your code. Check out the Compiling the code section of Learn You Some Erlang for more details.

Upvotes: 3

Related Questions