- 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.
- Windows系統管理與服務配置
- R語言編程指南
- Java設計模式及實踐
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- Hands-On Full Stack Development with Go
- Nginx Lua開發實戰
- Procedural Content Generation for C++ Game Development
- Test-Driven Machine Learning
- 小型編譯器設計實踐
- Orleans:構建高性能分布式Actor服務
- Java程序設計與項目案例教程
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計
- 深入淺出Python數據分析
- Practical Predictive Analytics
- Greenplum構建實時數據倉庫實踐