Skip to content

Instantly share code, notes, and snippets.

@billvanyo-zz
Created March 28, 2019 19:30
Show Gist options
  • Save billvanyo-zz/2c8d4207212ca214796948dc2a73a46e to your computer and use it in GitHub Desktop.
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".
/*
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