Functional Python Programming

(Wang) #1
Chapter 5

We can revise this slightly to create a higher-order function that separates the
wrapping from the other functions. We can define a function like this:


def cons_distance(distance, legs_iter):


return ((start, end, round(distance(start,end),4)) for start,
end in legs_iter)


This function will decompose each leg into two variables, start and end. These will
be used with the given distance() function to compute the distance between the
points. The result will build a more complex three tuple that includes the original
two legs and also the calculated result.


We can then rewrite our trip assignment to apply the haversine() function to
compute distances as follows:


path= float_from_pair(lat_lon_kml())


trip2= tuple(cons_distance(haversine, legs(iter(path))))


We've replaced a generator expression with a higher-order function, cons_
distance(). The function not only accepts a function as an argument, but it also
returns a generator expression.


A slightly different formulation of this is as follows:


def cons_distance3(distance, legs_iter):


return ( leg+(round(distance(*leg),4),) for leg in legs_iter)


This version makes the construction of a new object built up from an old object a bit
clearer. We're iterating through legs of a trip. We're computing the distance along a
leg. We're building new structures with the leg and the distance concatenated.


As both of these cons_distance() functions accept a function as an argument, we
can use this feature to provide an alternative distance formula. For example, we can
use the math.hypot(lat(start)-lat(end), lon(start)-lon(end)) method to
compute a less-correct plane distance along each leg.


In Chapter 10, The Functools Module, we'll show how to use the partial() function to
set a value for the R parameter of the haversine() function, which changes the units
in which the distance is calculated.

Free download pdf