- Functional Python Programming
- Steven F. Lott
- 414字
- 2021-08-27 19:20:30
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.
- Vue.js 3.x快速入門
- Expert C++
- Learning ArcGIS Pro 2
- NativeScript for Angular Mobile Development
- 你必須知道的204個Visual C++開發問題
- Java加密與解密的藝術
- Elasticsearch for Hadoop
- 自然語言處理Python進階
- Raspberry Pi Home Automation with Arduino(Second Edition)
- Learning Concurrent Programming in Scala
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- jQuery炫酷應用實例集錦
- 劍指大數據:企業級數據倉庫項目實戰(在線教育版)
- Mastering Akka
- Python 3.7從入門到精通(視頻教學版)