Skip to content

Instantly share code, notes, and snippets.

@Albertoimpl
Last active March 3, 2023 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Albertoimpl/3fbf55d5310e0b185e9a to your computer and use it in GitHub Desktop.
Save Albertoimpl/3fbf55d5310e0b185e9a to your computer and use it in GitHub Desktop.
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