Implementing recursive lambda with MethodHandle
Alex Blewitt
alex.blewitt at gmail.com
Tue Feb 23 03:03:05 PST 2010
On 23 Feb 2010, at 09:24, <David.Moss at ubs.com> wrote:
> I don't think 'this' should refer to the lambda.
>
> A lambda is a function belonging to it's enclosing scope (class), this
> means that 'this' needs to refer to the enclosing scope in order to be
> semantically correct.
Only if 'this' is defined as referring to the enclosing class. If 'this' is defined as referring to the lambda itself, then there is no semantic error.
> An additional syntax needs to be defined to refer to the lambda itself.
Whilst that may be the case, your code is solely focusing on 'simple' recursion, where the target of the lambda is a lambda invocation. That isn't necessarily the case. For example, one may use lambdas to provide an inversion of control, where the lambda itself is passed on as an argument:
process = #(Node n) { n.accept( process ) };
Simply omitting the target of a method invocation won't help here, because we need to pass the (self) reference rather than invoking internally. In other words, any proposed syntax should be able to act as the target of a lambda invocation (i.e. foo.()) as well as the lambda reference (i.e. foo).
> Public class C {
> /*
> * 1- Create a closure on the lambda variable.
That is one of the proposals so far.
> /*
> * 2- Reference the variable.
You're referring to it with 'this.lambda2', which only works if the lambda is an instance field of an enclosing class. It wouldn't work for a local defined lambda. One could put further restrictions (like recursive lambdas can only be defined at the top scope) but this seems an artificial and unnecessary restriction.
> /*
> * 3- Force recursive function variables to be final.
> *
This would prevent a redefinition case. Questions still arise with the question of mutable lambda references captured by other lambdas.
>
> /*
> * 4- Omit the variable name altogether.
This fails to allow the lambda to be passed by reference to other lambdas/functions/methods/classes inside the lambda.
> Personally, I would allow for 2 and 4 (and potentially 1, if lexical
> closures are a desired feature).
The problem with 2 is that it only works for instance fields; the problem with 4 is that it prevents passing the lambda by reference.
We could create a new keyword, like 'lambda', which acts as the self-lambda reference, but it seems a lot of work rather than just re-targeting 'this' to refer to the enclosing lambda scope, and allowing Outer.this to refer to the enclosing class instance.
Alex
More information about the lambda-dev
mailing list