Functional Python Programming

(Wang) #1
Chapter 3

We might have a set of colors that we will use as a kind of chroma-key: we will use
this color to create a mask that will be used to combine two images. Pragmatically,
a single color isn't appropriate but a small set of very similar colors works best.
In this case, we'll examine each pixel of an image file to see if the pixel is in the
chroma-key set or not. For this kind of processing, the chroma-key colors are loaded
into a frozenset before processing the target images. For more information, read
about chroma-key processing from the following link:


http://en.wikipedia.org/wiki/Chroma_key


As with mappings—specifically the Counter class—there are some algorithms that
can benefit from a memoized set of values. Some functions benefit from memoization
because a function is a mapping between domain values and range values, a job
for which a mapping works nicely. A few algorithms benefit from a memoized set,
which is stateful and grows as data is processed.


We'll return to memoization in Chapter 16, Optimizations and Improvements.


Summary


In this chapter, we looked closely at writing pure functions: free of side effects.
The bar is low here, since Python forces us to use the global statement to write
impure functions. We looked at generator functions and how we can use these
as the backbone of functional programming.


We also examined the built-in collection classes to show how they're used in the
functional paradigm. While the general ideal behind functional programming is
to limit the use of stateful variables, the collection objects are generally stateful
and, for many algorithms, also essential. Our goal is to be judicious in our use of
Python's nonfunctional features.


In the next two chapters, we'll look at higher-order functions: functions that
accept functions as arguments as well as returning functions. We'll start with
an exploration of the built-in higher-order functions. In later chapters, we'll look
at techniques for defining our own higher-order functions. We'll also look at
the itertools and functools modules and their higher-order functions in
later chapters.

Free download pdf