Functional Python Programming

(Wang) #1

Higher-order Functions


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



  • max() and min()

  • Lambda forms that we can use to simplify using higher-order functions

  • map()

  • filter()

  • iter()

  • sorted()


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. We'll defer this 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 a default
behavior as well as a higher-order function behavior. The function
is provided via the key= argument. The map() and filter()
functions take the function as the first positional argument.

Using max() and min() to find extrema


The max() and min() functions have a dual life. They are simple functions that apply
to collections. They are also higher-order functions. We can see their default behavior
as follows:





max(1, 2, 3)





3





max((1,2,3,4))





4


Both functions will accept an indefinite number of arguments. The functions are
designed to also accept a sequence or an iterable as the only argument and locate
the max (or min) of that iterable.

Free download pdf