Functional Python Programming

(Wang) #1

Recursions and Reductions


This can also be written as an iteration as follows:


def partition(key, data):


dictionary= defaultdict(list)


for head in data:


dictionary[key(head)].append(head)


return dictionary


When doing the tail-call optimization, the essential line of the code in the imperative
version will match the recursive definition. We've highlighted that line to emphasize
that the rewrite is intended to have the same outcome. The rest of the structure
represents the tail-call optimization we've adopted as a common way to work
around the Python limitations.


Writing more general group-by reductions


Once we have partitioned the raw data, we can compute various kinds of
reductions on the data elements in each partition. We might, for example,
want the northern-most point for the start of each leg in the distance bins.


We'll introduce some helper functions to decompose the tuple as follows:


start = lambda s, e, d: s


end = lambda s, e, d: e


dist = lambda s, e, d: d


latitude = lambda lat, lon: lat


longitude = lambda lat, lon: lon


Each of these helper functions expects a tuple object to be provided using the *
operator to map each element of the tuple to a separate parameter of the lambda.
Once the tuple is expanded into the s, e, and p parameters, it's reasonably obvious
to return the proper parameter by name. It's much more clear than trying to interpret
the tuple_arg[2] method.


Following is how we use these helper functions:





point = ((35.505665, -76.653664), (35.508335, -76.654999),
0.1731)








start(*point)





(35.505665, -76.653664)





end(*point)





(35.508335, -76.654999)





dist(*point)




Free download pdf