April 2018
Intermediate to advanced
408 pages
10h 42m
English
The sum() function can be defined using the partial(reduce, operator.add) function. This, too, gives us a hint as to how we can create other mappings and other reductions. We can define all of the commonly used reductions as partials instead of lambdas:
sum2 = partial(reduce, lambda x, y: x+y**2) count = partial(reduce, lambda x, y: x+1)
We can now use these functions via the sum2(some_data) or the count(some_iter) method. As we noted previously, it's not clear how much benefit this has. It's an important technique because it may be possible for a particularly complex calculation to be simplified using partial functions like this.