[erlang-questions] Self-referencing anonymous functions?

Christian Axelsson smiler@REDACTED
Fri Apr 3 13:00:35 CEST 2009


Christian wrote:
> 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.
> 
> Anyway.
> 
> 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.

True that.

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

This would allowed for scoped funs, much like the 'let'-keyword in ML,
thats something I've been missing a bit in Erlang. Although it's not
really that much of a hurdle :)

/Christian



More information about the erlang-questions mailing list