Maybe and the missing value
A value that may be missing
Maybe a is a type with two constructors: Nothing, for the absence of a value, and Just x, for a value that is there. A function that can fail returns Maybe instead of throwing, and the caller has to say what happens in the Nothing case, because the compiler will not let it forget.
data Maybe a = Nothing | Just a
That is the whole declaration, and it is in the Prelude. The type is a sum type like the ones of the last lessons, with a parameter: it works for any type of value, which is why it can wrap an Int, a String or a record without a new declaration each time.
lookup and fromMaybe
The standard example is a search in a list of pairs. lookup key table returns Just value or Nothing, and the type says so. Two consumers are worth knowing: fromMaybe default turns the absence into a value, and a case lets each branch do something different.
module Main (main) where
import Data.Maybe (fromMaybe, mapMaybe)
table :: [(String, Int)]
table = [("a", 1), ("b", 2)]
main :: IO ()
main = do
print (lookup "b" table)
print (lookup "z" table)
print (fromMaybe 0 (lookup "z" table))
print (mapMaybe (`lookup` table) ["a", "z", "b"])
ghc -Wall -O1 -o maybe maybe.hs
./maybe
Just 2
Nothing
0
[1,2]
The third line is the first decision point: fromMaybe 0 says that a missing key means zero here, and the type of the result is Int again. That is correct only if zero is a sensible default; when it is not, the Maybe should travel further instead of being collapsed early.
mapMaybe and the Maybe helpers
The Data.Maybe module collects the small functions that make Maybe comfortable. The most useful is mapMaybe :: (a -> Maybe b) -> [a] -> [b]: it maps a function that may fail over a list and drops the failures, which is a map and a filter in one pass.
mapMaybe (`lookup` table) ["a", "z", "b"] -- [1,2]
catMaybes [Just 1, Nothing, Just 3] -- [1,3]
isJust (Just 1) -- True
isNothing Nothing -- True
maybe 0 (+ 1) (Just 2) -- 3
maybe 0 (+ 1) Nothing -- 0
maybe is the eliminator: it takes a default, a function for the present case and a Maybe, and returns a plain value. Every consumer of a Maybe is one of these three shapes: collapse with a default, transform and drop, or match with case and handle both branches.
A function that can fail
Division by zero is the smallest failure in the language, and the lesson turns it into a type. safeDiv :: Int -> Int -> Maybe Int returns Nothing for a zero divisor, and a second function consumes the result with a case:
module Main (main) where
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)
ratio :: Int -> Int -> Maybe Double
ratio a b = case safeDiv a b of
Nothing -> Nothing
Just n -> Just (fromIntegral n / 2.0)
main :: IO ()
main = do
print (safeDiv 10 2)
print (safeDiv 10 0)
print (ratio 9 3)
ghc -Wall -O1 -o safediv safediv.hs
./safediv
Just 5
Nothing
Just 1.5
The second function propagates the failure without inspecting it: the Nothing branch returns Nothing, which is the same as doing nothing. In the next lesson on Either the failure carries a reason, and in the lesson on monads the propagation is written with >>= instead of a case. Both are the same idea: the type makes the failure part of the signature, and the compiler makes the caller handle it.
Exercises
- Write headMaybe :: [a] -> Maybe a with a pattern match, and use it on an empty and a non-empty list.
- Use mapMaybe to keep only the positive numbers of a list of Int.
- Replace fromMaybe 0 with a case and print a different message for the missing key.
- Write lookupTwice that looks up a key and then uses the value as a key of a second table.
- Explain why read "abc" :: Int throws while readMaybe does not, and which one belongs in a program that reads user input.
- Turn minimum into a total function with a Maybe result.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What are the two constructors of
Maybe a?Answer
NothingandJust aMaybe is defined as Nothing | Just a, absence or a present value.
-
What does
lookup "z" [("a", 1)]return?Answer
NothingThe key is not in the table, and lookup reports absence with Nothing.
-
What does
fromMaybe 0 (lookup "z" table)return when z is missing?Answer
0
fromMaybe replaces Nothing with the default and returns the value type.
-
What does
mapMaybe (lookuptable) ["a", "z", "b"]do?Answer
Looks up each key and keeps only the values that exist
mapMaybe maps the lookup and drops the Nothings, so the result is [1,2].
-
What does this program print?
module Main (main) where import Data.Maybe (fromMaybe) main :: IO () main = print (fromMaybe 7 (Just 3))Answer
3
The value is present, so fromMaybe returns it and ignores the default.
-
Why is a Maybe result better than an exception for a lookup?
Answer
The type makes the caller handle the missing case
The absence is in the type, so the compiler requires a branch for it.
-
What does
maybe 0 (+ 1) Nothingreturn?Answer
0
maybe returns the default for Nothing and applies the function for Just.
-
What does this program print? ``
module Main (main) where safeDiv :: Int -> Int -> Maybe Int safeDiv _ 0 = Nothing safeDiv a b = Just (adivb) main :: IO () main = print (safeDiv 10 0)``Answer
Nothing
The zero divisor matches the first equation, which returns Nothing instead of dividing.
-
What type does
Just 3have?Answer
Maybe awith a numeric a, hereMaybe IntJust wraps a value of any type; the number literal leaves the numeric type open until it is fixed.
-
What does
catMaybes [Just 1, Nothing, Just 3]return?Answer
[1,3]
catMaybes keeps the present values and drops the Nothings.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev