Skip to content

Instantly share code, notes, and snippets.

@jartur
Created March 25, 2015 11:53
Show Gist options
  • Save jartur/f98a11f8bb1d3b756520 to your computer and use it in GitHub Desktop.
Save jartur/f98a11f8bb1d3b756520 to your computer and use it in GitHub Desktop.
Java Y Combinator
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