Haskell Maybe Values
Maybe is a type that can hold a value or hold nothing. It lets a function report a missing result as a plain value.
Just wraps a present value
Just places a value inside a Maybe. The printed result keeps the word Just.
main :: IO ()
main = print (Just 5)Nothing shows a missing value
A score binding can hold Nothing when no score exists. The type line says the binding holds a Maybe Int.
score :: Maybe Int
score = Nothing
main :: IO ()
main = print scoreA lookup can miss
The findScore function returns Just for a known name. An unknown name matches the last equation and returns Nothing.
findScore :: String -> Maybe Int
findScore "Ana" = Just 84
findScore "Ben" = Just 92
findScore _ = Nothing
main :: IO ()
main = print (findScore "Cora")Example
findScore :: String -> Maybe Int
findScore "Ana" = Just 84
findScore "Ben" = Just 92
findScore _ = Nothing
message :: Maybe Int -> String
message (Just n) = "Found score " ++ show n
message Nothing = "No score found"
main :: IO ()
main = putStrLn (message (findScore "Ana"))Key points
- Maybe a: a type that holds a value of type a or holds nothing.
- Just: the constructor that wraps a value that is present.
- Nothing: the Maybe value that shows no value is present.
- Safe lookup: a function can return a Maybe value when a search might find nothing.
- Unwrap: pattern matching handles the Just case and the Nothing case.
In this example, findScore "Ana" returns Just 84. The message function matches Just 84 and builds the text with the number inside. The main action prints that text.
Note
Haskell uses Maybe instead of the null value found in many other languages.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does print (Just 5) print?