Haskell Working with Maybe
The maybe function turns a Maybe value into a plain value. It takes a fallback for the Nothing case and a function for the Just case.
Nothing gives the fallback
The double function doubles a number. With Nothing as the input, maybe skips double and returns the fallback 0.
double :: Int -> Int
double n = n * 2
main :: IO ()
main = print (maybe 0 double Nothing)Just gets the transform
With Just 15 as the input, maybe applies double to 15. The result is a plain number, not a Maybe value.
double :: Int -> Int
double n = n * 2
main :: IO ()
main = print (maybe 0 double (Just 15))Two safe steps in a nested case
The totalScore helper looks up the first name inside a case. A second case inside the first one looks up the second name and adds the two scores.
findScore :: String -> Maybe Int
findScore "Ana" = Just 10
findScore "Ben" = Just 20
findScore _ = Nothing
totalScore :: String -> String -> Maybe Int
totalScore a b =
case findScore a of
Nothing -> Nothing
Just x ->
case findScore b of
Nothing -> Nothing
Just y -> Just (x + y)
main :: IO ()
main = print (totalScore "Ana" "Ben")Example
findScore :: String -> Maybe Int
findScore "Ana" = Just 24
findScore "Ben" = Just 18
findScore _ = Nothing
double :: Int -> Int
double n = n * 2
main :: IO ()
main = print (maybe 0 double (findScore "Ana"))Key points
- maybe: a built-in function that turns a Maybe value into a plain value.
- Fallback: the plain value that maybe returns when the input is Nothing.
- Transform: the function that maybe applies to the value inside Just.
- Arguments: maybe takes a fallback, a function, and a Maybe value in that order.
- Nested case: a case inside a case can feed the result of one safe step into the next step.
In this example, findScore "Ana" returns Just 24. The maybe function applies double to 24 because the value is a Just. The main action prints the plain result 48.
Note
maybe is part of the Prelude, so no import is needed for it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
If double n = n * 2, what is maybe 0 double (Just 10)?