编写一个函数,计算Erlang列表中整数的总和 [英] Write a function that calculate the sum of integers in a list in Erlang
问题描述
$ 当我正在学习Erlang时,只需阅读书籍并进行自己的练习(不是作业),即使是在标题中提到的最简单的任务,我还在努力。 b $ b
这是我所做的:
我创建了一个名为sum.erl的文件,带有以下代码:
-module(mysum)。
-export([mysum / 1])。
mysum(L) - >
mysum(L,0)。
mysum([H | T],acc) - >
mysum(T,H + acc);
mysum([],acc) - >
acc。
然后我编译:
erl sum.erl
这需要我一个shell。在那里,我键入:
1> L = [1,3,7]。
[1,3,7]
2> mysum(L)。
**异常错误:未定义的shell命令mysum / 1
3> sum:mysum(L)。
**异常错误:未定义函数sum:mysum / 1
说什么?为什么我会收到这些错误,即使错误信息略有不同,我想也许他们的意思相差很远?
更新:新代码
-module(总和)。
-export([sum / 1])。
sum(L) - >
sum(L,0)。
sum([H | T],Acc))>
sum(T,H + Acc);
sum([],Acc) - >
加
然后
1> L = [1,2,3]。
[1,2,3]
2> sum:sum(L)。
**异常错误:无函数子句匹配总和:sum([1,2,3],0)
该文件应该称为 mysum.erl
,与 -module
指令。还有其他的是Erlang的编译器错误。
确保您使用 c(mysum)
在shell中(并且您在 mysum.erl
的目录中。
由于你的模块被命名为 mysum
,导出的函数名为 mysum
,所以你应该调用它: / p>
3&mysql:mysum(L)
此外,您将结果存储在 acc
中的变量应命名为 Acc
(资本a)否则,它是一个原子,一旦你调用 mysum(L,0)就会得到一个
因为没有子句处理 function_clause
0
作为第二个参数( 0
code> acc )。
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
).
这篇关于编写一个函数,计算Erlang列表中整数的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!