I recently came across this piece of code in Java. It involves Function and printing fibonacci numbers and it works.
public class AppLambdaSubstitution {
public static Function<Integer, Integer> Y(Function<Function<Integer, Integer>, Function<Integer, Integer>> f) {
return x -> f.apply(Y(f)).apply(x);
}
public static void main(String[] args) {
Function<Integer, Integer> fib = Y(
func -> x -> {
if (x < 2)
return x;
else
return func.apply(x - 1) + func.apply(x - 2);
});
IntStream.range(1,11).
mapToObj(Integer::valueOf).
map(fib).forEach(System.out::println);
}
}
The part that has me confused is return x -> f.apply(Y(f)).apply(x);
. Isn't Y(f)
a recursive call to the method Y
? We keep calling it with the Function f
as a parameter. To me, there's no base case for this recursive call to return from. Why is there no overflow resulting from an endless recursive call?