Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java 8 Trampoline for Tail Call Recursion
import java.math.BigInteger;
public class TailCallRecursion {
@FunctionalInterface
public interface Trampoline<V> {
V trampoline();
default V call() {
Object trampoline = this;
while (trampoline instanceof Trampoline) {
trampoline = ((Trampoline) trampoline).trampoline();
}
@SuppressWarnings("unchecked")
V value = (V) trampoline;
return value;
}
}
public static Trampoline factorial(final int n, final BigInteger accumulated) {
return () -> {
if (n <= 1) return accumulated;
return factorial(n - 1, accumulated.multiply(BigInteger.valueOf(n)));
};
}
public static void main(String[] args) {
System.out.println(factorial(10000, BigInteger.ONE).call());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment