Functional Python Programming

(Wang) #1
Chapter 2

For example, look at the following command snippet:





max(map(lambda yc: (yc[1],yc), year_cheese))





(33.5, (2007, 33.5))





_[1]





(2007, 33.5)


This fits the three-part pattern, although it might not be obvious how well it fits.


First, we wrap, using map(lambda yc: (yc[1],yc), year_cheese). This will
transform each item into a two tuple with a key followed by the original item.
In this example, the comparison key is merely yc[1].


Second, do the processing using the max() function. Since each piece of data has
been simplified to a two tuple with position zero used for comparison, we don't
really need the higher-order function feature of the max() function. The default
behavior of the max() function is exactly what we require.


Finally, we unwrap using the subscript [1]. This will pick the second element
of the two tuple selected by the max() function.


This kind of wrap and unwrap is so common that some languages have special
functions with names like fst() and snd() that we can use as a function prefix
instead of a syntactic suffix of [0] or [1]. We can use this idea to modify our
wrap-process-unwrap example, as follows:


snd= lambda x: x[1]


snd( max(map(lambda yc: (yc[1],yc), year_cheese)))


We defined a snd() function to pick the second item from a tuple. This provides
us with an easier-to-read version of unwrap(process(wrap())). We used
map(lambda... , year_cheese) to wrap our raw data items. We used max()
function as the processing and, finally, the snd() function to extract the second
item from the tuple.


In Chapter 13, Conditional Expressions and the Operator Module, we'll look at some
alternatives to lambda functions like fst() and snd().


Strict and non-strict evaluation


Functional programming's efficiency stems, in part, from being able to defer a
computation until it's required. The idea of lazy or non-strict evaluation is very
helpful. It's so helpful that Python already offers this feature.

Free download pdf