Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: Returning a function from a function

Tags:

erlang

I know Erlang supports anonymous functions. My question is, can I return a function from a function then call that returned function from outside? If so, how do I do it? I know this is possible in many languages such as C and Python. Here is what I tried to do, but it doesn't work:

-module(test).
-export([run/0]).

test() ->
    io:format("toasters", []).

bagel() ->
    test.

run() ->
    (bagel())().

Results:

Erlang/OTP 17 [erts-6.2] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V6.2  (abort with ^G)
1> c(test).
test.erl:4: Warning: function test/0 is unused
{ok,test}
2> test:run().
** exception error: bad function test
     in function  test:run/0 (test.erl, line 11)
3> 
like image 926
sudo Avatar asked Mar 16 '23 18:03

sudo


1 Answers

Ah, here we go:

-module(test).
-export([run/0]).

test() ->
    io:format("toasters", []).

bagel() ->
    fun test/0. % <- This is what I needed to change.

run() ->
    (bagel())().

I was looking here for an answer, and they didn't explicitly state it, but the example near the top gave me the hint just now.

like image 139
sudo Avatar answered Mar 25 '23 06:03

sudo