3 Composition

 

This chapter covers

  • Combining types into compound types
  • Combining types as either-or types
  • Visitor pattern implementations
  • Algebraic data types

In the previous chapter we looked at some common primitive types which form the building blocks of a type system. In this chapter we’ll look at ways to combine them to define new types.

We’ll cover compound types, which group values of several types together. We’ll look at how naming members gives meaning to data and lowers the chance of misinterpretation, and how we can ensure values are well-formed when they need to meet certain constraints.

Next, we’ll go over “either-or” types, which contain a single value from one of several types. We will look at some common such types like optional types, either types, and variants, and a few applications of these. For example, we’ll see how returning a result or an error is usually safer than returning a result and an error.

As an application of “either-or” types, we’ll take a look at the visitor design pattern and contrast an implementation that leverages class-hierarchies with an implementation that uses a variant to store and operate on objects.

Finally, we’ll provide a description of algebraic data types or ADTs, and see how they relate to the topics discussed in this chapter.

3.1       Compound Types

3.1.1 Tuples

3.1.2 Assigning Meaning

3.1.3 Maintaining Invariants

3.1.4 Exercise

3.2       Expressing “Either-Or” with Types

3.2.1 Enumerations

3.2.2 Optional Types

3.2.3 Result or Error

3.2.4 Variants

3.2.5 Exercises

3.3       The Visitor Pattern

3.3.1 A Naïve Implementation

3.3.2 Using the Visitor Pattern

3.3.3 Visiting a Variant

3.3.4 Exercise

3.4       Algebraic Data Types

3.4.1 Product Types

3.4.2 Sum Types

3.4.3 Exercises

3.5       Summary

3.6       Answers to Exercises

sitemap