If i call the test(), it doesnt work. Can someone explain this ?.
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(debug, [test1]).
If i call the test(), it doesnt work. Can someone explain this ?.
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(debug, [test1]).
First, C
variable hasn't been used at all, and second you should wrap the test1
with a fun/end
:
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(C, [fun() -> test1() end]).
test1
on its own is simply an atom, not a reference to the local function. To create a reference to the function use fun Function/Arity as below.
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = F(), io:format("~p ", [Val]) end,
lists:foreach(C, [fun test1/0]).
You could also construct an anonymous function that calls test1
like this: fun() -> test1() end
, but there's no reason to that unless you have additional values you want to pass in or the like.
The other two answers do actually answer the question. I just want to add to them.
I expect that you want to be able to pass an atom and call the function with that name. This is not possible for local functions. It is very possible for exported functions though.
So you can do something like (my only change is to add "?MODULE:", and to change "debug" to "C"):
-module(anony).
-export([test/0, test1/0]).
test1() -> "hello".
test() ->
C = fun(F) -> Val = ?MODULE:F(), io:format("~p ", [Val]) end,
lists:foreach(C, [test1]).