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.