Lesson 19. The Maybe type: dealing with missing values
After reading lesson 19, you’ll be able to
- Understand the Maybe type
- Use the Maybe type to handle missing values
- Design programs with Maybe types
Just as type classes can often be much more abstract than interfaces in OOP, parameterized types play a much larger role than generics do in most languages. This lesson introduces an important parameterized type: Maybe. Unlike List or Map, which represent containers for values, Maybe is the first of many types you’ll see that represents a context for a value. Maybe types represent values that might be missing. In most languages, a missing value is represented by the null value. By using a context representing a value that might be missing, the Maybe type allows you to write much safer code. Because of the power of the Maybe type, errors related to null values are systematically removed from Haskell programs.
Consider this
Suppose you have a simple Map that contains grocery items and indicates the number of them that you need to purchase:
You accidentally look up MILK instead of Milk. What behavior should you expect from your Map, and how can you handle this type of mistake so that your programs can be sure to run safely even in the presence of missing values in your Map?