Created
October 13, 2017 22:33
-
-
Save claudemartin/8d686f2a597cf33f1199893f373ec599 to your computer and use it in GitHub Desktop.
Y combinator in Java 8
This file contains hidden or 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 ch.claude_martin; | |
import java.util.function.Function; | |
import java.util.function.UnaryOperator; | |
public class YComb { | |
interface Fn2Op<T> extends Function<Fn2Op<T>, UnaryOperator<T>> { | |
@Override | |
UnaryOperator<T> apply(Fn2Op<T> x); | |
} | |
public static void main(String args[]) { | |
UnaryOperator<UnaryOperator<Long>> factorial = f -> n -> { | |
if (n == 0) | |
return 1L; | |
else | |
return n * f.apply(n - 1); | |
}; | |
System.out.println(Y(Long.parseLong(args[0]), factorial)); | |
} | |
private static <T> T Y(T arg, UnaryOperator<UnaryOperator<T>> factorial) { | |
return ((Function<UnaryOperator<UnaryOperator<T>>, UnaryOperator<T>>) r -> ((Fn2Op<T>) f -> f.apply(f)) | |
.apply(f -> r.apply(x -> f.apply(f).apply(x)))).apply(factorial).apply(arg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment