Erlang “unbound variable” when calling a function

♀尐吖头ヾ 提交于 2019-12-07 14:16:24

问题


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

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

I am still getting used to anonymous functions and erlang in general coming an object-oriented world. Any help would be appreciated.


回答1:


Each Erlang module, as described here, should consist of a sequence of attributes and function declarations, each terminated by period (.)

But this line:

Foo = fun(X) -> X * X end.

... is neither and should be written as follows instead:

foo(X) -> X * X.

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



回答2:


The previous solution is correct, but you can resolve the problem with this code too:

-module(bakery).
-export([cake/1]).

cake(0) -> [];
cake(N) when N > 0 ->
   Foo = fun(X) -> X * X end,
   [ Foo(2) | cake(N-1) ].

Regards.



来源:https://stackoverflow.com/questions/12719103/erlang-unbound-variable-when-calling-a-function

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