Created
March 28, 2019 19:30
-
-
Save billvanyo-zz/2c8d4207212ca214796948dc2a73a46e to your computer and use it in GitHub Desktop.
Demo of recursive factorial function using anonymous lambda expressions and a "Y combinator".
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
/* | |
A demonstration of recursive implementation of the factorial function using anonymous | |
lambda expressions and a "Y combinator". | |
see: https://en.wikipedia.org/wiki/Fixed-point_combinator | |
*/ | |
import java.math.BigInteger; | |
public class YCombinator { | |
interface SelfApplicable<T> { | |
T apply(SelfApplicable<T> a); | |
} | |
interface Func<X, Y> { | |
Y apply(X x); | |
} | |
public static void main(String[] args) { | |
BigInteger zero = BigInteger.valueOf(0); | |
BigInteger one = BigInteger.valueOf(1); | |
BigInteger fifty = BigInteger.valueOf(50); | |
BigInteger tenThousand = BigInteger.valueOf(10000); | |
for (BigInteger i = BigInteger.valueOf(1); i.compareTo(fifty) != 1; i = i.add(one)) { | |
System.out.print(i + "! = "); | |
System.out.println(((SelfApplicable<Func<Func<Func<BigInteger, BigInteger>, Func<BigInteger, BigInteger>>, Func<BigInteger, BigInteger>>>) | |
y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x)) | |
.apply(y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x)) | |
.apply(f -> n -> n.compareTo(zero) == 0 ? one : n.multiply(f.apply(n.subtract(one)))) | |
.apply(i)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment