Chapter 5. Function types

 

This chapter covers

  • Simplifying the strategy pattern with function types
  • Implementing a state machine without switch statements
  • Implementing lazy values as lambdas
  • Using the fundamental data processing algorithms map, filter, and reduce to reduce code duplication

We covered basic types and types built up from them. We also looked at how we can declare new types to increase the safety of our programs and enforce various constraints on their values. This is about as far as we can get with algebraic data types or the ability to combine types as sum types and product types.

The next feature of type systems we are going to cover, which unlocks a whole new world of expressiveness, is the ability to type functions. If we can name function types and use functions in the same places we use values of other types—as variables, arguments, and function returns—we can simplify the implementation of several common constructs and abstract common algorithms to library functions.

In this chapter, we’ll look at how we can simplify the implementation of the strategy design pattern. (We’ll also have a quick refresher on the pattern, in case you forgot it.) Then we’ll talk about state machines and how they can be implemented more succinctly with function properties. We’ll cover lazy values, or how we can defer expensive computation in the hope that we won’t need it. Finally, we’ll deep dive into the fundamental map(), reduce(), and filter() algorithms.

5.1. A simple strategy pattern

5.2. A state machine without switch statements

5.3. Avoiding expensive computation with lazy values

5.4. Using map, filter, and reduce

5.5. Functional programming

Summary

Answers to exercises

sitemap