Last active
August 29, 2015 14:00
-
-
Save timyates/11304666 to your computer and use it in GitHub Desktop.
Y Combinator based factorial in Java 8
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
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