Functional Python Programming

(Wang) #1
Chapter 10

max= lambda iterable: reduce(lambda x, y: x if x > y else y,
iterable)


The sum2() reduction function is the sum of squares, useful for computing standard
deviation of a set of samples. This sum() reduction function mimics the built-in
sum() function. The count() reduction function is similar to the len() function, but
it can work on an iterable, where the len() function can only work on a materialized
collection object.


The min() and max() functions mimic the built-in reductions. Because the first item
of the iterable is used for initialization, these two functions will work properly. If we
provided any initial value to these reduce() functions, we might incorrectly use a
value that never occurred in the original iterable.


Combining map() and reduce()


We can see how to build higher-order functions around these simple definitions.
We'll show a simplistic map-reduce function that combines the map() and reduce()
functions as follows:


def map_reduce(map_fun, reduce_fun, iterable):


return reduce(reduce_fun, map(map_fun, iterable))


We've created a composite function from the map() and reduce() functions that take
three arguments: the mapping, the reduction operation, and the iterable or sequence
to process.


We can build a sum-squared reduction using the map() and reduce() functions
separately as follows:


def sum2_mr(iterable):


return map_reduce(lambda y: y**2, lambda x,y: x+y, iterable)


In this case, we've used the lambda y: y**2 parameter as a mapping to square
each value. The reduction is simply lambda x,y: x+y parameter. We don't need to
explicitly provide an initial value because the initial value will be the first item in the
iterable after the map() function has squared it.


The lambda x,y: x+y parameter is merely the + operator. Python offers all of the
arithmetic operators as short functions in the operator module. Following is how
we can slightly simplify our map-reduce operation:


import operator


def sum2_mr2(iterable):


return map_reduce(lambda y: y**2, operator.add, iterable)

Free download pdf