jgonet
Recursive anonymous functions
What’s the state of recursive anonymous functions now? It was mentioned a while ago, when this feature was being introduced in OTP 17. What’s the syntax for defining those? This isn’t working:
f = fn
(0, acc) -> acc
(num, acc) -> f.(num-1, acc+1)
end
Most Liked
Qqwy
I do not know the exact state at this time, but I did have a discussion with @sasajuric and @michalmuskala about this while at the Code BEAM Lite Amsterdam.
Some notes:
- There is no current syntax in Elixir to define the ‘named anonymous functions’ that were added to Erlang in OTP 17 directly.
- However, one can argue that it is not really required. In Erlang, a problem was that you were unable to define a module inside the shell, only being able to define one-off anonymous functions. That really makes it difficult when you want to test out a piece of code that should call itself recursively. (In Elixir’s IEx this is not a problem, as it allows defining new modules in the shell.)
- Of course, the ‘classical’ way to do this, the Y-Combinator, is a possibility both in Erlang and Elixir. However, using this is (a) rather slow and (b) beginner-unfriendly, because it is difficult to read. But then again, it’s manually-entered shell-code we are talking about, in which these arguments might not be as strong. When writing modules, why not, instead of a self-recursing anonymous function, define it as a private, named function instead?
- It is possible to define an macro that wraps a function in a similar way that the Y-Combinator construction does, in a way that might be more understandable for users (say
fn_rec. No alterations to Elixir’s core are necessary to do this. (But this also does not use Erlang’s ‘named anonymous functions’).
An example of how (4) could look when used would be:
fn_rec
_, 0, acc -> acc
myfun, num, acc -> myfun.(num - 1, acc + 1)
end
(although when using this syntax, I’d prefer writing it as:
fn_rec myfun, num, acc ->
case num do
0 -> acc
_ -> myfun.(num - 1, acc + 1)
end
)
or possibly:
fn_rec myfun do
0, acc -> acc
num, acc -> myfun.(num - 1, acc + 1)
end
One of the things I do not know, is how performance compares between:
- using a y-combinator-style approach (where no new names are defined).
- using an indirectly-threaded approach where the macro defines a new name
- using the Erlang’s ‘named anonymous functions’ directly.
(I expect the y-combinator to be slow, and directly using the Erlang feature to be the fastest, but I do not know how by how much, or if it is enough to justify adding it as a built-in construct to the Elixir language itself.)
peerreynders
iex(1)> f = fn
...(1)> (_, 0, acc) -> acc
...(1)> (g, num, acc) -> g.(g, num-1, acc+1)
...(1)> end
#Function<18.128620087/3 in :erl_eval.expr/5>
iex(2)>
nil
iex(3)> f.(f,10,10)
20
iex(4)>
Functions are values …
peerreynders
1> G = fun
1> F (0, Acc) -> Acc;
1> F (Num, Acc) -> F(Num - 1, Acc + 1)
1> end.
#Fun<erl_eval.36.128620087>
2> G(10,10).
20
3>
Even though this feature now exists in Erlang the points are:
- There already is a solution in Elixir (and Erlang pre-17.0) that works even if it isn’t elegant.
- How often does a real need for recursive anonymous functions actually come up, given that recursion is well supported with named functions within actual code (rather than the shell)?
Erlang and by extension Elixir are pragmatic languages.
I contend that anonymous functions are an overused feature which are even more prevalent in Elixir because of the existence of the shorthand notation.
I see the primary value of an anonymous function in it’s closure (i.e. its connection to the scope that created it) - that should be the reason for using it. More often than not they are used simply for notational convenience even though quite often code becomes less readable.
The Erlang named anonymous function example can be quite easily emulated with a mixture of an anonymous function for its closure and a named function to do the real work:
# file: Demo.ex
# Original: https://learnyousomeerlang.com/higher-order-functions#highlighter_833032
#
defmodule Demo do
def prepare_alarm(room) do
IO.puts("Alarm set in #{room}")
fn -> loop(room) end
end
defp loop(room) do
IO.puts("Alarm tripped in #{room}! Call Batman!")
Process.sleep(500)
loop(room)
end
end
iex(1)> c("Demo.ex")
[Demo]
iex(2)> alarm_ready = Demo.prepare_alarm("bathroom")
Alarm set in bathroom
#Function<0.61175415/0 in Demo.prepare_alarm/1>
iex(3)> alarm_ready.()
Alarm tripped in bathroom! Call Batman!
Alarm tripped in bathroom! Call Batman!
Alarm tripped in bathroom! Call Batman!
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
(v)ersion (k)ill (D)b-tables (d)istribution
a
Last Post!
igsp7
An example from Learn Functional Programming with Elixir by Ulisses Almeida :
iex> fact_gen = fn me ->
fn
0 -> 1
x when x > 0 -> x * me.(me).(x - 1)
end
end
iex> factorial = fact_gen.(fact_gen)
iex> factorial.(5)
120
Popular in Discussions
Other popular topics
Chat & Discussions>Discussions
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









