Book Image

Functional Python Programming. - Second Edition

Book Image

Functional Python Programming. - Second Edition

Overview of this book

If you’re a Python developer who wants to discover how to take the power of functional programming (FP) and bring it into your own programs, then this book is essential for you, even if you know next to nothing about the paradigm. Starting with a general overview of functional concepts, you’ll explore common functional features such as first-class and higher-order functions, pure functions, and more. You’ll see how these are accomplished in Python 3.6 to give you the core foundations you’ll build upon. After that, you’ll discover common functional optimizations for Python to help your apps reach even higher speeds. You’ll learn FP concepts such as lazy evaluation using Python’s generator functions and expressions. Moving forward, you’ll learn to design and implement decorators to create composite functions. You'll also explore data preparation techniques and data exploration in depth, and see how the Python standard library fits the functional programming model. Finally, to top off your journey into the world of functional Python, you’ll at look at the PyMonad project and some larger examples to put everything into perspective.
Table of Contents (22 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

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 is as follows:
def facti(n: int) -> int:
    if n == 0: return 1
    f = 1
    for i in range(2,n):
        f = f*i
    return f

When the recursion appears at the end of a simple function, it's described as a tail-call optimization. Many compilers will optimize this into a loop. Python doesn't have an optimizing compiler and doesn't do this kind...