Book Image

Functional Python Programming

By : Steven F. Lott, Steven F. Lott
Book Image

Functional Python Programming

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (23 chapters)
Functional Python Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Recursion instead of a explicit loop state


Functional programs don't rely on loops and the associated overhead of tracking the state of loops. Instead, functional programs try to rely on the much simpler approach of recursive functions. In some languages, the programs are written as recursions, but Tail-Call Optimization (TCO) by the compiler changes them to loops. We'll introduce some recursion here and examine it closely in Chapter 6, Recursions and Reductions.

We'll look at a simple iteration to test a number for being prime. A prime number is a natural number, evenly divisible by only 1 and itself. We can create a naïve and poorly performing algorithm to determine if a number has any factors between two and the number. This algorithm has the advantage of simplicity; it works acceptably for solving Project Euler problems. Read up on Miller-Rabin primality tests for a much better algorithm.

We'll use the term coprime to mean that two numbers have only 1 as their common factor. The numbers...