How do you obtain reference to function

I was wondering can we obtain a reference to function in Erlang and pass it around like we do in Elixir?

I am looking for equivalent of this code:

iex(1)> defmodule Foo do
...(1)> def bar do
...(1)> IO.puts "foo"
...(1)> end
...(1)> end
{:module, Foo,
 <<70, 79, 82, 49, 0, 0, 3, 136, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 95,
   0, 0, 0, 10, 10, 69, 108, 105, 120, 105, 114, 46, 70, 111, 111, 8, 95, 95,
   105, 110, 102, 111, 95, 95, 9, 102, 117, ...>>, {:bar, 0}}
iex(2)> f = &Foo.bar/0
&Foo.bar/0
iex(3)> f.()
foo
:ok

So far I’ve been wrapping around my function calls in anonymous function in Erlang, and I can pass this around just fine. Was just wondering if there is a construct like in Elixir to make this quicker.

fun module:fun/arity

:slight_smile:

5 Likes

Perfect. So a working example would be:

Eshell V9.0  (abort with ^G)
1> F = fun io:format/2.        
#Fun<io.format.2>
2> F("~s~n", ["Hello, Erlang!"]).
Hello, Erlang!
ok

Thank you so much @arkgil

2 Likes