Tail recursion optimizations

In Chapter 6, Recursions and Reductions, among many others, we looked at how a simple recursion can be optimized into a for loop. We'll use the following simple recursive definition of factorial as an example:

The general approach to optimizing a recrusion is this:

  • Design the recursion. This means the base case and the recursive cases as a simple function that can be tested and shown to be correct, but slow. Here's the simple definition:
def fact(n: int) -> int:
    if n == 0: return 1
    else: return n*fact(n-1)  
  • If the recursion has a simple call at the end, replace the recursive case with a for loop. The definition ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.