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:

groceries :: Map.Map String Int
groceries = Map.fromList [("Milk",1),("Candy bars",10),
("Cheese blocks",2)]

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?

19.1. Introducing Maybe: solving missing values with types

 

19.2. The problem with null

 
 
 

19.3. Computing with Maybe

 

19.4. Back to the lab! More-complex computation with Maybe

 
 
 

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