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

廉价感情. 提交于 2019-12-24 04:08:09

问题


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)

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7408454/write-a-function-that-calculate-the-sum-of-integers-in-a-list-in-erlang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!