laan_sachin
laan_sachin

Reputation: 19

Erlang - Anonymouos Function

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

Upvotes: 1

Views: 304

Answers (3)

Daniel Luna
Daniel Luna

Reputation: 1979

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

Upvotes: 3

Boris Pavlović
Boris Pavlović

Reputation: 64632

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

Upvotes: 2

cthulahoops
cthulahoops

Reputation: 3835

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.

Upvotes: 7

Related Questions