开发者

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

开发者 https://www.devze.com 2023-04-04 20:52 出处:网络
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.

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)


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消