Created
April 18, 2013 18:27
-
-
Save danveloper/5415057 to your computer and use it in GitHub Desktop.
Trampoline in Java 8 with Lambdas and interface defaults
This file contains 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
public class TrampolineLambda { | |
interface TrampolineFunction<T, R> { | |
R apply(T...obj); | |
public default Object trampoline(T...objs) { | |
Object result = apply(objs); | |
if (!(result instanceof TrampolineFunction)) { | |
return result; | |
} else { | |
return this; | |
} | |
} | |
} | |
// Wrap the call in a TrampolineFunction so that we can avoid StackOverflowError | |
static TrampolineFunction<Integer, Object> fibTrampoline = (Integer...objs) -> { | |
Integer n = objs[0]; | |
Integer a = objs.length >= 2 ? objs[1] : 0; | |
Integer b = objs.length >= 3 ? objs[2] : 1; | |
if (n == 0) return a; | |
else return fibTrampoline.trampoline(n-1, b, a+b); | |
}; | |
// Eventually will get a StackOverflowError | |
static IntFunction<Integer> regularFib = (int n) -> { | |
if (n == 0 || n == 1) return n; | |
return regularFib.apply(n - 1) + regularFib.apply(n - 2); | |
}; | |
public static void main(String[] args) { | |
// Prints "1556111435" | |
System.out.println(fibTrampoline.apply(1000)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://github.com/groovy/groovy-core/blob/master/src/main/groovy/lang/TrampolineClosure.java