Functional Python Programming

(Wang) #1
Chapter 5

We need to exercise some caution when designing mappings that combine too
many transformations in a single function. As far as possible, we want to avoid
creating functions that fail to be succinct or expressive of a single idea. As Python
doesn't have an optimizing compiler, we might be forced to manually optimize
slow applications by combining functions. We need to do this kind of optimization
reluctantly, only after profiling a poorly performing program.


Unwrapping data while mapping


When we use a construct such as (f(x) for x, y in C), we've used multiple
assignment in the for statement to unwrap a multi-valued tuple and then apply a
function. The whole expression is a mapping. This is a common Python optimization
to change the structure and apply a function.


We'll use our trip data from Chapter 4, Working with Collections. The following is a
concrete example of unwrapping while mapping:


def convert(conversion, trip):


return (conversion(distance) for start, end, distance in trip)


This higher-order function would be supported by conversion functions that we can
apply to our raw data as follows:


to_miles = lambda nm: nm5280/6076.12
to_km = lambda nm: nm
1.852
to_nm = lambda nm: nm


This function would then be used as follows to extract distance and apply a
conversion function:


convert(to_miles, trip)


As we're unwrapping, the result will be a sequence of floating-point values.
The results are as follows:


[20.397120559090908, 35.37291511060606, ..., 44.652462240151515]


This convert() function is highly specific to our start-end-distance trip data
structure, as the for loop decomposes that three tuple.


We can build a more general solution for this kind of unwrapping while
mapping a design pattern. It suffers from being a bit more complex. First, we
need general-purpose decomposition functions like the following code snippet:


fst= lambda x: x[0]
snd= lambda x: x[1]
sel2= lambda x: x[2]

Free download pdf