views:

112

answers:

3

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]).
+2  A: 

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]).
Boris Pavlović
Your `fun() -> test1 end` doesn't call `test1` at all, it just returns the atom `test1`.
cthulahoops
@cthulahoops Thanks, you are right (+1)
Boris Pavlović
+7  A: 

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.

cthulahoops
+3  A: 

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]).
Daniel Luna
An interesting alternative. I wonder how it compares to the other answer (using fun test1/0 to make an explicit function reference) in terms of performance.
Daniel Yankowsky
My solution will be a little bit slower because of the "external" function call. On the other hand they solve two different problems.
Daniel Luna