Anonymous recursion: Difference between revisions

Line 966:
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</lang>
 
A different approach: the function always receives itself as the first argument, and when recursing, makes sure to pass the called function as the first argument also
Same thing as the above, but modified so that the function is uncurried:
<lang python>>>> from functools import partial
>>> Y = lambda f: partial(lambda x: x(x))(lambda y: lambda *args: f(y(y), *args)f)
>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f, n-1) + f(f, n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</lang>
Anonymous user