Functional Python Programming
上QQ阅读APP看书,第一时间看更新

Higher-Order Functions

A very important feature of the functional programming paradigm is higher-order functions. These are functions that accept functions as arguments or return functions as results. Python offers several kinds of higher-order functions. We'll look at them and some logical extensions.

As we can see, there are three varieties of higher-order functions as follows:

  • Functions that accept functions as one (or more) of their arguments
  • Functions that return a function
  • Functions that accept a function and return a function, a combination of the preceding two features

Python offers several higher-order functions of the first variety. We'll look at these built-in higher-order functions in this chapter. We'll look at a few of the library modules that offer higher-order functions in later chapters.

The idea of a function that emits functions can seem a bit odd. However, when we look at a Callable class, the class definition is a function that returns  Callable objects when evaluated. This is one example of a function that creates another function.

Functions that accept functions and create functions include complex callable classes as well as function decorators. We'll introduce decorators in this chapter, but defer deeper consideration of decorators until Chapter 11, Decorator Design Techniques.

Sometimes, we wish that Python had higher-order versions of the collection functions from the previous chapter. In this chapter, we'll show the reduce(extract()) design pattern to perform a reduction of specific fields extracted from a larger tuple. We'll also look at defining our own version of these common collection-processing functions.

In this chapter, we'll look at the following functions:

  • max() and min()
  • map()
  • filter()
  • iter()
  • sorted()

We'll also look at lambda forms that we can use to simplify using higher-order functions.

There are a number of higher-order functions in the itertools module. We'll look at this module in Chapter 8, The Itertools Module and Chapter 9, More Itertools Techniques.

Additionally, the functools module provides a general-purpose reduce() function. We'll look at this in Chapter 10, The Functools Module because it's not as generally applicable as the other higher-order functions in this chapter.

The max() and min() functions are reductions; they create a single value from a collection. The other functions are mappings. They don't reduce the input to a single value.

The max(), min(), and sorted() functions have both a default behavior as well as a higher-order function behavior. A function can be provided via the key= argument. The map() and filter() functions take the function as the first positional argument.