🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Maybe Monad

The Maybe monad is the Monad instance for Maybe. It chains steps that may succeed with a value or fail with Nothing.

A Just value lets the next step run

The first step gives Just 8. The next step adds 2 inside Maybe.

main :: IO ()
main = print (Just 8 >>= (\x -> Just (x + 2)))

A failing step skips the later steps

The middle step gives Nothing. The addition never runs and the result is Nothing.

failStep :: Int -> Maybe Int
failStep _ = Nothing
main :: IO ()
main = print (Just 8 >>= failStep >>= (\y -> Just (y + 1)))

A safe step returns Nothing for bad input

Safe division by 2 gives Just 5. Safe division by 0 gives Nothing.

safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x `div` y)
main :: IO ()
main = do
  print (safeDiv 10 2)
  print (safeDiv 10 0)

Example

safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x `div` y)
main :: IO ()
main = do
  print (safeDiv 100 4 >>= (\x -> Just (x + 5)))
  print (safeDiv 100 0 >>= (\x -> Just (x + 5)))

Key points

  • Maybe monad: the chain for steps where any step may give Nothing.
  • Success: a Just value lets the next step run with its contents.
  • Failure: a Nothing value skips every later step and gives Nothing.
  • Use the Maybe monad to write a chain of checks without testing each result by hand.
  • Safe step: a helper that returns Nothing for a bad input and Just for a good input.

In this example, safe division of 100 by 4 gives Just 25 and then bind adds 5 to give Just 30. Safe division by 0 gives Nothing, so the second chain also gives Nothing.

Note

Maybe carries no message about why a step failed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does Just 5 >>= (\x -> Nothing) give when Nothing is a Maybe Int?