Skip to the content ForoHackers
Log inJoin

Monad tutorial no. 48: it is just `>>=` for Maybe, I promise

Functional programmingHaskellType theory
#1152 · monad_tutorial_no_47 · · Report

I refuse to use a burrito. Just one example and one rule.

You have three functions that can fail:

parseAge  :: String -> Maybe Int
checkAdult :: Int -> Maybe Int
describe  :: Int -> Maybe String

Without any abstraction, chaining them looks like this:

case parseAge s of
  Nothing -> Nothing
  Just a  -> case checkAdult a of
    Nothing -> Nothing
    Just b  -> describe b

The same pattern, "if it failed, stop; otherwise pass the value on", repeats at every step. >>= is that pattern, written once:

parseAge s >>= checkAdult >>= describe

And do notation is the same thing with nicer clothes:

do a <- parseAge s
   b <- checkAdult a
   describe b

A monad is a type with a way to say "put a plain value inside" (return) and a way to say "run the next step if there is a value" (>>=). For Maybe the "next step" is skipped on Nothing. For lists it runs once per element. For IO it runs after the previous action. Same shape, different meaning of "next".

That is all of it. The other 47 tutorials were mostly about the burrito.

#1923 · lambda_llama · · Report

Best opening line of the year. I would add that >>= has to obey three laws (left identity, right identity, associativity) so that do blocks behave the way your eyes expect. Those laws are the actual definition. The burrito is decoration.

#1924 · it_works_on_my_vm · · Report

Newcomer question. If >>= for Maybe just stops at the first Nothing, how do I learn which step failed? The result is the same Nothing whichever one it was.

#1925 · monad_tutorial_no_47 · · Report

Good question, and the answer is the next tutorial: use Either String instead of Maybe. Same >>=, but a failure carries a message, so you get Left "not an adult" instead of silence. The pattern did not change, only the container did.

#1926 · polyglot_parser · · Report

As a former linguist: "monad" explained via Maybe is the first time I thought "oh, this is just a grammar for sequencing with a side condition". Thanks for not mentioning category theory.

Log in or join to reply.