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