10 Generic Algorithms and Iterators
In this chapter:
- Using map(), filter(), and reduce()beyond arrays
- Using a set of common algorithms to solve a wide range of problems
- Ensuring 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 various data structures.
We looked at one version 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 which work with iterators, so we can apply them to binary trees, lists, arrays, and any other iterable data structure.
map(), filter(), and reduce() are not unique. We’ll talk about other generic algorithms and algorithm libraries 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.