Chapter 4. Higher-Order Functions
In the last chapter we saw an iterator algebra that builds on the
itertools module. In some ways, higher-order functions (often
abbreviated as “HOFs”) provide similar building blocks to express
complex concepts by combining simpler functions into new functions. In
general, a higher-order function is simply a function that takes one
or more functions as arguments and/or produces a function as a result.
Many interesting abstractions are available here. They allow chaining and
combining higher-order functions in a manner analogous to how we can
combine functions in itertools to produce new iterables.
A few useful higher-order functions are contained in the functools
module, and a few others are built-ins. It is common the think of
map(), filter(), and functools.reduce() as the most basic building
blocks of higher-order functions, and most functional programming
languages use these functions as their primitives (occasionally under
other names). Almost as basic as map/filter/reduce as a building block
is currying. In Python, currying is spelled as partial(), and is contained in the functools module—this is a function that will take another function, along with zero or more arguments to pre-fill, and return a function of fewer arguments that operates as the input function would when those arguments are passed to it.
The built-in functions map() and filter() are equivalent to comprehensions—especially now that generator comprehensions are available—and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access