Chapter Review Questions

Chapter Review Questions#

  1. In your own words, what makes a function pure?

  2. Classify each of the following as pure or side-effecting:

    1. len(items)

    2. print(items)

    3. items.append(x)

    4. sorted(items)

  3. What is a higher-order function? Give one example that takes a function and one that returns a function.

  4. Three built-in shapes of data processing.

    1. What does map do?

    2. What does filter do?

    3. What does functools.reduce do?

  5. Rewrite [n * n for n in nums if n % 2 == 0] using map and filter. Which version do you find clearer, and why?

  6. Why does reduce take a start value, and what does that value have to do with empty sequences?

  7. What is a closure? In make_multiplier from this chapter, what does the returned function “remember”?

  8. The counter built with nonlocal is convenient but no longer pure. Explain why, and what you give up.

  9. What does functools.partial(power, exponent=2) produce, and how is it different from calling power?

  10. If h = compose(f, g), which of f and g runs first when you call h(x)?

  11. Aliasing.

    a = [1, 2, 3]
    b = a
    b.append(4)
    
    1. What is a afterward?

    2. How would you append to b without changing a?

  12. Describe the functional core, imperative shell pattern. Why is the core easy to test and the shell hard?

  13. Why does a dynamically typed language like Python rely on testing more than a statically typed one does?

  14. Three layers of testing.

    1. What is a doctest, and where does it live?

    2. How does a property-based test differ from an example-based test?

    3. Give one property (invariant, round-trip, or oracle) you could test for a function that sorts a list.

  15. Name the three equivalent models of computation discussed in the overview, and say which one functional programming descends from.