Created
April 1, 2016 03:51
-
-
Save amaembo/6bca6a6b6ae53260af3404297dc95399 to your computer and use it in GitHub Desktop.
Fibonacci numbers via MethodHandles (see also https://github.com/kuksenko/quiz )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.lang.invoke.MethodHandles.*; | |
import java.lang.invoke.*; | |
public class MyClass { | |
public static boolean less(int i, int cnt) { | |
return i<=cnt; | |
} | |
public static void main(String[] args) throws Throwable { | |
MethodHandle sum = lookup().findStatic(Integer.class, "sum", MethodType.methodType(int.class, int.class, int.class)); | |
MethodHandle less = lookup().findStatic(MyClass.class, "less", MethodType.methodType(boolean.class, int.class, int.class)); | |
MethodHandle id = identity(int.class); | |
MethodHandle one = constant(int.class, 1); | |
MethodHandle[][] loop = {{ | |
dropArguments(one, 0, int.class), | |
insertArguments(sum, 1 , 1), | |
dropArguments(less, 1, int.class, int.class, int.class), | |
dropArguments(dropArguments(id, 0, int.class, int.class), 3, int.class, int.class) | |
}, | |
{ null, dropArguments(sum, 0, int.class, int.class) }, | |
{ one, dropArguments(id, 0, int.class, int.class, int.class) }, | |
{ one, dropArguments(id, 0, int.class) }}; | |
MethodHandle mhLoop = loop(loop); | |
System.out.println((int)mhLoop.invokeExact(8)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment