Je suis récemment tombé sur ce morceau de code en Java. Il implique la fonction et l'impression des numéros de fibonacci et cela fonctionne.Comment est-ce morceau de l'appel récursif lambda en Java fonctionne
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);
}
}
La partie qui m'a confondu est return x -> f.apply(Y(f)).apply(x);
. Y(f)
n'est pas un appel récursif à la méthode Y
? Nous continuons à l'appeler avec la fonction f
en tant que paramètre. Pour moi, il n'y a pas de cas de base pour cet appel récursif de retour. Pourquoi n'y a-t-il pas de débordement résultant d'un appel récursif sans fin?
Le 'Y (f)' appel est à l'intérieur d'un lambda , et que lambda n'est exécuté que si 'f' choisit de l'appeler. – 4castle
https://en.wikipedia.org/wiki/Fixed-point_combinator – pvg