Functional Python Programming

(Wang) #1
Chapter 1

The sum of a sequence has a simple, recursive definition:


def sum(seq):
if len(seq) == 0: return 0
return seq[0] + sum(seq[1:])

We've defined the sum of a sequence in two cases: the base case states that the
sum of a zero length sequence is 0, while the recursive case states that the sum
of a sequence is the first value plus the sum of the rest of the sequence. Since the
recursive definition depends on a shorter sequence, we can be sure that it will
(eventually) devolve to the base case.


The + operator on the last line of the preceding example and the initial value of 0 in
the base case characterize the equation as a sum. If we change the operator to * and
the initial value to 1, it would just as easily compute a product. We'll return to this
simple idea of generalization in the following chapters.


Similarly, a sequence of values can have a simple, recursive definition, as follows:


def until(n, filter_func, v):
if v == n: return []
if filter_func(v): return [v] + until( n, filter_func, v+1 )
else: return until(n, filter_func, v+1)

In this function, we've compared a given value, v, against the upper bound, n.
If v reaches the upper bound, the resulting list must be empty. This is the base
case for the given recursion.


There are two more cases defined by the given filter_func() function. If the value
of v is passed by the filter_func() function, we'll create a very small list, containing
one element, and append the remaining values of the until() function to this list. If
the value of v is rejected by the filter_func() function, this value is ignored and the
result is simply defined by the remaining values of the until() function.


We can see that the value of v will increase from an initial value until it reaches n,
assuring us that we'll reach the base case soon.


Here's how we can use the until() function to generate the multiples of 3 or 5.
First, we'll define a handy lambda object to filter values:


mult_3_5= lambda x: x%3==0 or x%5==0

(We will use lambdas to emphasize succinct definitions of simple functions.
Anything more complex than a one-line expression requires the def statement.)

Free download pdf