Erlang“未绑定变量”当调用函数时 [英] Erlang "unbound variable" when calling a function
问题描述
我试图将一个整数参数N传递给 cake
,并返回一个大小为N的平方的列表(为了示例的目的)。例如面包店:蛋糕(3)=> [4,4,4]
I am trying to pass an integer parameter N to cake
and return a list of size N of the square of 2 (for the sake of example). e.g. bakery:cake(3) => [4,4,4]
这是我迄今为止所尝试的:
Here is what I have attempted so far:
-module(bakery).
-export([cake/1]).
Foo = fun(X) -> X * X end.
cake(0) -> [];
cake(N) when N > 0 -> [ Foo(2) | cake(N-1) ].
当我编译代码 c(bakery)。
在erl中,我得到以下错误跟踪:
When I compile the code c(bakery).
in erl however, I get the following error trace:
bakery.erl:4: syntax error before: Foo
bakery.erl:7: variable 'Foo' is unbound
error
我是仍然习惯于匿名功能和erlang一般来说面向对象的世界。任何帮助将不胜感激。
I am still getting used to anonymous functions and erlang in general coming an object-oriented world. Any help would be appreciated.
推荐答案
每个Erlang模块,如这里应该包含一系列属性和函数声明,每个都由句号(。)终止。
Each Erlang module, as described here, should consist of a sequence of attributes and function declarations, each terminated by period (.)
但这行:
Foo = fun(X) -> X * X end.
...既不是,也应该写成如下:
... is neither and should be written as follows instead:
foo(X) -> X * X.
foo
是小写在这里因为此行是函数声明,其中函数名应为原子码。
foo
is lowercase here, because this line is a function declaration, where function name should be an atom.
所以最后你的模块看起来像这样:
So in the end your module will look like this:
-module(bakery).
-export([cake/1]).
foo(X) -> X * X.
cake(0) -> [];
cake(N) when N > 0 -> [ foo(2) | cake(N-1) ].
这篇关于Erlang“未绑定变量”当调用函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!