Functional Python Programming

(Wang) #1

Working with Collections


a = sin(Δ_lat/2)2 + cos(lat_1)cos(lat_2)sin(Δ_lon/2)2
c = 2*asin(sqrt(a))


return R * c


This is a relatively simple implementation copied from the World Wide Web.


The following is how we might use our collection of functions to examine some KML
data and produce a sequence of distances:


trip= ((start, end, round(haversine(start, end),4))
for start,end in legs(float_from_pair(lat_lon_kml())))
for start, end, dist in trip:
print(start, end, dist)


The essence of the processing is the generator expression assigned to the trip
variable. We've assembled three tuples with a start, end, and the distance from start
to end. The start and end pairs come from the legs() function. The legs() function
works with floating-point data built from the latitude-longitude pairs
extracted from a KML file.


The output looks like the following command snippet:


(37.54901619777347, -76.33029518659048) (37.840832, -76.273834)
17.7246
(37.840832, -76.273834) (38.331501, -76.459503) 30.7382
(38.331501, -76.459503) (38.845501, -76.537331) 31.0756
(36.843334, -76.298668) (37.549, -76.331169) 42.3962
(37.549, -76.331169) (38.330166, -76.458504) 47.2866
(38.330166, -76.458504) (38.976334, -76.473503) 38.8019


Each individual processing step has been defined succinctly. The overview, similarly,
can be expressed succinctly as a composition of functions and generator expressions.


Clearly, there are several further processing steps we might like to apply to
this data. First, of course, is to use the format() method of a string to produce
better-looking output.


More importantly, there are a number of aggregate values we'd like to extract from
this data. We'll call these values reductions of the available data. We'd like to reduce
the data to get the maximum and minimum latitude—for example, to show the
extreme North and South ends of this route. We'd like to reduce the data to get
the maximum distance in one leg as well as the total distance for all legs.

Free download pdf