Erlang: Returning a function from a function
I know Erlang supports anonymous functions. My question is, can I return a function from a function and then call the returned function from the outside? If so, how do I do it? I know this is possible in many languages ββlike C and Python. Here's 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>
+3
sudo
source
to share
1 answer
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 searched here for an answer and they didn't explicitly state it, but the example at the top gave me a hint.
+5
sudo
source
to share