Summarizing a collection – how to reduce
In the introduction to this chapter, we noted that there are three common processing patterns: map, filter, and reduce. We've seen examples of mapping in the Applying transformations to a collection recipe, and examples of filtering in the Picking a subset – three ways to filter recipe. It's relatively easy to see how these become very generic operations.
Mapping applies a simple function to all elements of a collection. {M(x): x ∈ C} applies a function, M, to each item, x, of a larger collection, C. In Python, it can look like this:
(M(x) for x in C)
Or, we can use the built-in map()
function to remove the boilerplate and simplify it to this:
map(M, c)
Similarly, filtering uses a function to select elements from a collection. {x: x ∈ C if F(x)} uses a function, F, to determine whether to pass or reject an item, x, from a larger collection, C. We can express this in a variety of ways in Python, one of which is like this:
filter...