Functional Python Programming

(Wang) #1

Recursions and Reductions


Following is a higher-level parser command snippet:


def color_palette(headers, row_iter):
name, columns = headers
colors = tuple(Color(int(r), int(g), int(b), " ".join(name))
for r,g,b,*name in row_iter)
return name, columns, colors


This function will work with the output of the lower-level row_iter_gpl() parser: it
requires the headers and the iterator. This function will use the multiple assignment
to separate the color numbers and the remaining words into four variables, r, g, b,
and name. The use of the *name parameter assures that all remaining values will be
assigned to names as a tuple. The " ".join(name) method then concatenates the
words into a single space-separated string.


Following is how we can use this two-tier parser:


with open("crayola.gpl") as source:
name, columns, colors = color_palette(*row_iter_gpl(source))
print(name, columns, colors)


We've applied the higher-level parser to the results of the lower-level parser.
This will return the headers and a tuple built from the sequence of Color objects.


Summary


In this chapter, we've looked at two significant functional programming topics.
We've looked at recursions in some detail. Many functional programming language
compilers will optimize a recursive function to transform a call in the tail of the
function to a loop. In Python, we must do the tail-call optimization manually by
using an explicit for loop instead of a purely function recursion.


We've also looked at reduction algorithms including sum(), count(), max(), and
min() functions. We looked at the collections.Counter() function and related
groupby() reductions.


We've also looked at how parsing (and lexical scanning) are similar to reductions
since they transform sequences of tokens (or sequences of characters) into higher-
order collections with more complex properties. We've examined a design pattern that
decomposes parsing into a lower level that tries to produce tuples of raw strings and a
higher level that creates more useful application objects.


In the next chapter, we'll look at some techniques appropriate to working with
namedtuples and other immutable data structures. We'll look at techniques that
make stateful objects unnecessary. While stateful objects aren't purely functional, the
idea of a class hierarchy can be used to package related method function definitions.

Free download pdf