Functional Python Programming

(Wang) #1

Higher-order Functions


We've created a sequence of pairs drawn from a single flat list. Each pair will have
two adjacent values. The zip() function properly stops when the shorter list is
exhausted. This zip( x, x[1:]) pattern only works for materialized sequences and
the iterable created by the range() function.


We created pairs so that we can apply the haversine() function to each pair to
compute the distance between the two points on the path. The following is how it
looks in one sequence of steps:


from ch02_ex3 import lat_lon_kml, float_from_pair, haversine


path= tuple(float_from_pair(lat_lon_kml()))


distances1= map( lambda s_e: (s_e[0], s_e[1], haversine(*s_e)),
zip(path, path[1:]))


We've loaded the essential sequence of waypoints into the path variable. This is an
ordered sequence of latitude-longitude pairs. As we're going to use the zip(path,
path[1:]) design pattern, we must have a materialized sequence and not a simple
iterable.


The results of the zip() function will be pairs that have a start and end. We want our
output to be a triple with the start, end, and distance. The lambda we're using will
decompose the original two tuple and create a new three tuple from the start, end,
and distance.


As noted previously, we can simplify this by using a clever feature of the map()
function, which is as follows:


distances2= map(lambda s, e: (s, e, haversine(s, e)), path, path[1:])


Note that we've provided a function and two iterables to the map() function. The
map() function will take the next item from each iterable and apply those two values
as the arguments to the given function. In this case, the given function is a lambda
that creates the desired three tuple from the start, end, and distance.


The formal definition for the map() function states that it will do star-map processing
with an indefinite number of iterables. It will take items from each iterable to create a
tuple of argument values for the given function.


Using the filter() function to pass or reject data


The job of the filter() function is to use and apply a decision function called a
predicate to each value in a collection. A decision of True means that the value
is passed; otherwise, the value is rejected. The itertools module includes

Free download pdf