Created
March 25, 2015 11:53
-
-
Save jartur/f98a11f8bb1d3b756520 to your computer and use it in GitHub Desktop.
Java Y Combinator
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
public class Y<T> implements Function<Function<Function<T, T>, Function<T, T>>, Function<T, T>> { | |
@FunctionalInterface | |
private interface FuncToFunc<F> extends Function<FuncToFunc<F>, F> {} | |
@Override | |
public Function<T, T> apply(Function<Function<T, T>, Function<T, T>> r) { | |
final FuncToFunc<Function<T, T>> funcToFunc = f -> f.apply(f); | |
return funcToFunc.apply(f -> r.apply(x -> f.apply(f).apply(x))); | |
} | |
public static void main(String[] args) { | |
final Function<Integer, Integer> factorial = new Y<Integer>().apply(fact -> n -> { | |
if (n == 0) return 1; | |
return n * fact.apply(n - 1); | |
}); | |
System.out.println(factorial.apply(10)); | |
System.out.println(factorial.apply(5)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment