Chapter 10. Generic algorithms and iterators

 

This chapter covers

  • Using map(), filter(), and reduce()beyond arrays
  • Using a set of common algorithms to solve a wide range of problems
  • Ensuring that a generic type supports a required contract
  • Enabling various algorithms with different iterator categories
  • Implementing adaptive algorithms

This chapter is all about generic algorithms—reusable algorithms that work on various data types and data structures.

We looked at one version each of map(), filter(), and reduce() in chapter 5, when we discussed higher-order functions. Those functions operated on arrays, but as we saw in the previous chapters, iterators provide a nice abstraction over any data structure. We’ll start by implementing generic versions of these three algorithms that work with iterators, so we can apply them to binary trees, lists, arrays, and any other iterable data structures.

map(), filter(), and reduce() are not unique. We’ll talk about other generic algorithms and algorithm libraries that are available to most modern programming languages. We’ll see why we should replace most loops with calls to library algorithms. We’ll also briefly talk about fluent APIs and what a user-friendly interface for algorithms looks like.

10.1. Better map(), filter(), reduce()

10.2. Common algorithms

10.3. Constraining type parameters

10.4. Efficient reverse and other algorithms using iterators

10.5. Adaptive algorithms

Summary

Answers to exercises

sitemap