9 Algebraic data types and pattern matching

 

This chapter covers

  • Removing invalid states from programs
  • Using algebraic data types
  • Handling errors with optional values and variants
  • Creating overloaded function objects
  • Handling algebraic data types through pattern matching

During the course of this book, we’ve tackled a few problems the program state introduces. You’ve seen how to design software without mutable state and how to implement data structures that are efficient to copy. But we still haven’t dealt with all the problems of program state: we haven’t covered unexpected or invalid states.

Consider the following situation. Suppose you have an application that counts the total number of words on a web page. The program can start counting as soon as it retrieves part of the web page. It has three basic states:

  • Initial state —The counting process hasn’t started yet.
  • Counting state —The web page is being retrieved, and counting is in progress.
  • Final state —The web page is fully retrieved, and all the words have been counted.

When you implement something like this, you usually create a class to contain all the data you need. You end up with a class that contains the handler through which the web page is accessed (a socket or a data stream), the counter to contain the number of words, and flags that indicate whether the process has started and whether it has finished.

You could have a structure like this:

9.1 Algebraic data types

 
 
 

9.1.1 Sum types through inheritance

 
 

9.1.2 Sum types through unions and std::variant

 
 
 
 

9.1.3 Implementing specific states

 
 

9.1.4 Special sum type: Optional values

 
 
 

9.1.5 Sum types for error handling

 

9.2 Domain modeling with algebraic data types

 
 
 

9.2.1 The naive approach, and where it falls short

 
 
 
 

9.2.2 A more sophisticated approach: Top-down design

 
 

9.3 Better handling of algebraic data types with pattern matching

 
 

9.4 Powerful pattern matching with the Mach7 library

 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest