Functional Python Programming

(Wang) #1
Chapter 5

We've looked at several kinds of higher-order functions that work with a collection
of values. Throughout the previous chapters, we've hinted around at several
different design patterns for higher-order collection and scalar functions.
The following is a broad classification:



  • Return a Generator. A higher-order function can return a generator
    expression. We consider the function higher-order because it didn't return
    scalar values or collections of values. Some of these higher-order
    functions also accept functions as arguments.

  • Act as a Generator. Some function examples use the yield statement to
    make them first-class generator functions. The value of a generator function
    is an iterable collection of values that are evaluated lazily. We suggest that
    a generator function is essentially indistinguishable from a function that
    returns a generator expression. Both are non-strict. Both can yield a sequence
    of values. For this reason, we'll also consider generator functions as higher
    order. Built-in functions such as map() and filter() fall into this category.

  • Materialize a Collection. Some functions must return a materialized
    collection object: list, tuple, set, or mapping. These kinds of functions
    can be of a higher order if they have a function as part of the arguments.
    Otherwise, they're ordinary functions that happen to work with
    collections.

  • Reduce a Collection. Some functions work with an iterable (or a collection
    object) and create a scalar result. The len() and sum() functions are
    examples of this. We can create higher-order reductions when we accept
    a function as an argument. We'll return to this in the next chapter.

  • Scalar. Some functions act on individual data items. These can be
    higher-order functions if they accept another function as an argument.


As we design our own software, we can pick and choose among these established
design patterns.

Free download pdf