Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active August 29, 2015 14:00
Show Gist options
  • Save timyates/11304666 to your computer and use it in GitHub Desktop.
Save timyates/11304666 to your computer and use it in GitHub Desktop.
Y Combinator based factorial in Java 8
package test;
import java.math.BigInteger;
import java.util.function.Function;
public class YCombinatorFactorial<T> {
private interface Improver<T> {
Function<T,T> apply( Improver<T> f ) ;
}
private Function<T,T> Y( final Function<Function<T,T>,Function<T,T>> r ) {
return ((Improver<T>)f -> f.apply( f )).apply( f -> r.apply( x -> f.apply( f ).apply( x ) ) ) ;
}
public static void main( String[] args ) {
YCombinatorFactorial<BigInteger> yf = new YCombinatorFactorial<BigInteger>() ;
BigInteger result = yf.Y(
f -> n -> n.equals( BigInteger.ZERO ) ?
BigInteger.ONE :
n.multiply( f.apply(n.subtract( BigInteger.ONE ) ) ) ).apply( BigInteger.valueOf( 100 ) ) ;
System.out.println( result );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment