Functional Python Programming

(Wang) #1
Chapter 4

We'll need to create a pipeline of simpler transformation functions. Above, we arrived
at flt= ((float(lat), float(lon)) for lat,lon in lat_lon_kml()). We can
exploit the substitution rule for functions and replace a complex expression such as
(float(lat), float(lon)) for lat,lon in lat_lon_kml()) with a function
that has the same value, in this case, float_from_pair(lat_lon_kml()). This kind
of refactoring allows us to be sure that a simplification has the same effect as a more
complex expression.


There are some simplifications that we'll look at in Chapter 5, Higher-order Functions.
We will revisit this in Chapter 6, Recursions and Reductions to see how to apply these
simplifications to the file-parsing problem.


Applying generator expressions to scalar functions


We'll look cat a more complex kind of generator expression to map data values from
one kind of data to another. In this case, we'll apply a fairly complex function to
individual data values created by a generator.


We'll call these non-generator functions scalar, as they work with simple scalar
values. To work with collections of data, a scalar function will be embedded in a
generator expression.


To continue the example started earlier, we'll provide a haversine function and then
use a generator expression to apply a scalar haversine() function to a sequence of
pairs from our KML file.


The haversine() function looks like following:


from math import radians, sin, cos, sqrt, asin


MI= 3959
NM= 3440
KM= 6371


def haversine( point1, point2, R=NM ):
lat_1, lon_1= point1
lat_2, lon_2= point2


Δ_lat = radians(lat_2 - lat_1)
Δ_lon = radians(lon_2 - lon_1)
lat_1 = radians(lat_1)
lat_2 = radians(lat_2)

Free download pdf