On Fri, 7 Aug 2020 at 22:35, Terry Reedy <tjre...@udel.edu> wrote: > This is a common misconception. Linear iteration and tail recursion are > equivalent. The issue is calculating values once versus multiple times. > Here is the fast recursion equivalent to the fast iteration. > > def fib(n, pair=(1,0)): > previous, current = pair > if n: > return fib(n-1, (current, previous + current)) > else: > return current > > for i in range(10): print(fib(i), end=' ') > # 0 1 1 2 3 5 8 13 21 34
It seems to me a sort of not persistent caching. If you do: fib(very_large_number) without calculating any previous Fibonacci number before, it will be very slow and you could have a stack overflow. A language with tail call optimization will execute it faster and with less memory. Otherwise why asyncio de-facto implemented tail optimization? PS: it seems there's a module that implement tail call: https://github.com/baruchel/tco -- https://mail.python.org/mailman/listinfo/python-list