Functional Python Programming

(Wang) #1
Chapter 5

The by_dist() function picks apart the three items in each leg tuple and returns the
distance item. We'll use this with the max() and min() functions.


The max() and min() functions both accept an iterable and a function as arguments.
The keyword parameter key= is used by all of Python's higher-order functions to
provide a function that will be used to extract the necessary key value.


We can use the following to help conceptualize how the max() function uses
the key function:


wrap= ((key(leg),leg) for leg in trip)


return max(wrap)[1]


The max() and min() functions behave as if the given key function is being used
to wrap each item in the sequence into a two tuple, process the two tuple, and then
decompose the two tuple to return the original value.


Using Python lambda forms


In many cases, the definition of a helper function requires too much code. Often,
we can digest the key function to a single expression. It can seem wasteful to have to
write both def and return statements to wrap a single expression.


Python offers the lambda form as a way to simplify using higher-order functions.
A lambda form allows us to define a small, anonymous function. The function's body
is limited to a single expression.


The following is an example of using a simple lambda expression as the key:


long, short = max(trip, key=lambda leg: leg[2]),
min(trip, key=lambda leg: leg[2])


print(long, short)


The lambda we've used will be given an item from the sequence; in this case, each
leg three tuple will be given to the lambda. The lambda argument variable, leg, is
assigned and the expression, leg[2], is evaluated, plucking the distance from the
three tuple.


In the rare case that a lambda is never reused, this form is ideal. It's common,
however, to need to reuse the lambda objects. Since copy-and-paste is such
a bad idea, what's the alternative?


We can always define a function.

Free download pdf