Implementing recursive lambda with MethodHandle
Rémi Forax
forax at univ-mlv.fr
Mon Feb 22 03:52:15 PST 2010
To summarize, there is three ways to have recursive lambda:
1) No recursive lambda:
If you need a recursive function, create it has a private method
and call it in the lambda
(this is my favorite choice :)
static int sum(int x) {
return (x==0)?0:x + sum(x-1);
}
#int(int) a= #int(int x) {
return sum(x);
};
2) this refers to the current lambda
In that case you can use this.() to do the recursive call.
#int(int) a= #int(int x) {
return (x==0)?0:x + this.(x-1);
};
3) allow a reference to a lambda to be used inside a lambda
#int(int) a= #int(int x) {
return (x==0)?0:x + a.(x-1);
};
How to implement solution 2 or 3 with method handles ?
First, it's not simple because a method handle is an
object that contains a function pointer to a method,
so there is no dedicated class.
You have to first create the method handle and then inject itself to be
available
in the body of the function referenced.
Because injecting the method handle creates a new method handle
so you have a eggs and chicken problem that you can solve with an array.
static int $lambda$1(MethodHandle[] mh, int x) {
return (x==0)?0:x + mh[0].invokeGenerics(x-1);
}
MethodHandle mh = #$lambda$1(MethodHandle, int)
MethodHandle[] array = {null};
mh = mh.bind(array);
array[0] = mh;
Rather ugly, isn't it ?
cheers,
Rémi
More information about the lambda-dev
mailing list