[erlang-questions] Self-referencing anonymous functions?

Christian chsu79@REDACTED
Fri Apr 3 12:39:05 CEST 2009

On Fri, Apr 3, 2009 at 10:45, Christian Axelsson <smiler@REDACTED> wrote:
> Joe Armstrong wrote:
>> 1> Cost = fun(F, [{N,C}|T]) -> N*C + F(F, T);(_,[])-> 0 end.
>> #Fun<erl_eval.12.113037538>
>> 2> Cost(Cost, [{2,3},{4,5}]).
>> Now you know why the book didn't have any examples of this :-)
> I've noticed that aswell :)
> Would it be a bad idea to introduce a keyword for self referencing
> anonymous functions?

That discussion has been had several times on this list. I think
nothing is done because those that are capable of doing it don't feel
that it is important. The shell is just used for basic inspection and
evaluation, not for building systems. Get distel to compile into real
modules if you want more interactive development. If you want recusion
in real modules you can define a named function. Giving non-trivial
things a name is generally a good thing. It makes it much easier to
talk about.


Introducing a magical keyword that refers to the surrounding closure
would be a bad thing anyway. First for introducing yet another
keyword. Secondly because it is only referring to one surrounding fun
when erlang allow funs to return funs that return funs, and so on.

The better approach would be to add an optional name that is scoped to
the fun-body. This way you can have multiple nested funs and they can
refer to the outer funs or itself, and the programmer can give them
meaningful names.

More information about the erlang-questions mailing list