Erlang “unbound variable” when calling a function

2019-05-10 05:46发布

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.

标签: erlang
2条回答
家丑人穷心不美
2楼-- · 2019-05-10 06:25

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.

查看更多
Melony?
3楼-- · 2019-05-10 06:44

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) ].
查看更多
登录 后发表回答