Functional Python Programming

(Wang) #1

Higher-order Functions


Generally, this count_not_none() object will behave like any other Python function.
The use is somewhat simpler than our previous example of sum_filter_f().


We can use the count_not_None() function as follows:


N= count_not_none(data)


Instead of using sum_filter_f() funtion:


N= sum_filterf(valid, count, data)


The count_not_none() function, based on a Callable, doesn't require quite so
many arguments as a conventional function. This makes it superficially simpler to
use. However, it can also make it somewhat more obscure because the details of
how the function works are in two places in the source code: where the function
was created as an instance of the Callable class and where the function was used.


Looking at some of the design patterns


The max(), min(), and sorted() functions have a default behavior without a
key= function. They can be customized by providing a function that defines how
to compute a key from the available data. For many of our examples, the key()
function has been a simple extraction of available data. This isn't a requirement;
the key() function can do anything.


Imagine the following method: max(trip, key=random.randint()). Generally,
we try not to have have key() functions that do something obscure.


The use of a key= function is a common design pattern. Our functions can easily
follow this pattern.


We've also looked at lambda forms that we can use to simplify using higher-order
functions. One significant advantage of using lambda forms is that it follows the
functional paradigm very closely. When writing more conventional functions,
we can create imperative programs that might clutter an otherwise succinct and
expressive functional design.

Free download pdf