Functional Python Programming

(Wang) #1

Higher-order Functions


We can also assign lambdas to variables, by doing something like this:


start= lambda x: x[0]


end = lambda x: x[1]


dist = lambda x: x[2]


A lambda is a callable object and can be used like a function. The following is an
example at the interactive prompt:





leg = ((27.154167, -80.195663), (29.195168, -81.002998),
129.7748)








start= lambda x: x[0]








end = lambda x: x[1]








dist = lambda x: x[2]








dist(leg)





129.7748


Python offers us two ways to assign meaningful names to elements of tuples:
namedtuples and a collection of lambdas. Both are equivalent.


To extend this example, we'll look at how we get the latitude or longitude value
of the starting or ending point. This is done by defining some additional lambdas.


The following is a continuation of the interactive session:





start(leg)





(27.154167, -80.195663)











lat = lambda x: x[0]








lon = lambda x: x[1]








lat(start(leg))





27.154167


There's no clear advantage to lambdas over namedtuples. A set of lambdas to extract
fields requires more lines of code to define than a namedtuple. On the other hand,
we can use a prefix function notation, which might be easier to read in a functional
programing context. More importantly, as we'll see in the sorted() example later,
the lambdas can be used more effectively than namedtuple attribute names by
sorted(), min(), and max().

Free download pdf