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 using 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.1.1 A Functional Strategy

5.1.2 Typing Functions

5.1.3 Strategy Implementations

5.1.4 First-Class Functions

5.1.5 Exercises

5.2       A State Machine without Switch Statements

5.2.1 Early Programming with Types

5.2.2 State Machines

5.2.3 State Machine Implementation Recap

5.2.4 Exercises

5.3       Avoiding Expensive Computation with Lazy Values

5.3.1 Lambdas

5.3.2 Exercise

5.4       Map, Filter, Reduce

5.4.1 Map

5.4.2 Filter

5.4.3 Reduce

5.4.4 Library Support

5.4.5 Exercises

5.5       Functional Programming

5.6       Summary

5.7       Answers to Exercises

sitemap