Recursive anonymous functions

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.)

8 Likes