Last active
March 3, 2023 17:49
-
-
Save Albertoimpl/3fbf55d5310e0b185e9a to your computer and use it in GitHub Desktop.
Java 8 Trampoline for Tail Call Recursion
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
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