jgonet

jgonet

Popcorn Core Team

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

Qqwy

TypeCheck Core Team

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:

  1. There is no current syntax in Elixir to define the ‘named anonymous functions’ that were added to Erlang in OTP 17 directly.
  2. 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.)
  3. 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?
  4. 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

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

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:

  1. There already is a solution in Elixir (and Erlang pre-17.0) that works even if it isn’t elegant.
  2. 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

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

Where Next?

Popular in Discussions Top

rower687
Hi all, I’ve been reading a lot about the “let it crash” term and how supervising processes and the whole messaging passing make an elixi...
New
joeerl
I’m playing with Elixir - It’s fun. I think @rvirding does give Elixir courses these days. Re: files and database - when I given Erlang ...
New
PragTob
Hey everyone, this has been brewing in my head some time and it came up again while reading Adopting Elixir. GenServers, supervisors et...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
owaisqayum
I have a sample string sentence = "Hello, world ... 123 *** ^%&amp;*())^% %%:&gt;" From this string, I want to only keep the integers, ...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
matthias_toepp
I’d love to hear what people think about Wisp, the new Gleam web framework started by Gleam’s primary creator Louis Pilfold. Gleam, alon...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New

We're in Beta

About us Mission Statement