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.

10.1  Better Map, Filter, Reduce

10.1.1    Map

10.1.2    Filter

10.1.3    Reduce

10.1.4    Filter/Reduce Pipeline

10.1.5    Exercises

10.2  Common Algorithms

10.2.1    Algorithms Instead of Loops

10.2.2    Implementing a Fluent Pipeline

10.2.3    Exercises

10.3  Constraining Type Parameters

10.3.1    Generic Data Structures with Type Constraints

10.3.2    Generic Algorithms with Type Constraints

10.3.3    Exercise

10.4  Efficient Reverse and Other Algorithms Using Iterators

10.4.1    Iterator Building Blocks

10.4.2    A Useful Find

10.4.3    An Efficient Reverse

10.4.4    Efficient Element Retrieval

10.4.5    Iterators Recap

10.4.6    Exercises

10.5  Adaptive Algorithms

10.5.1    Exercise

10.6  Summary

10.7  Answers to Exercises

sitemap