Skip to content
Maybe Monad
step 1/5

Reading — step 1 of 5

Learn

~1 min readMonads in Practice

Monad is the type class for chained computations in a context. Maybe is the simplest practical example.

-- Without monad: ugly nested matching
lookupAge name = case findUser name of
    Nothing -> Nothing
    Just user -> case userProfile user of
        Nothing -> Nothing
        Just profile -> Just (profileAge profile)

With >>= (the bind operator):

lookupAge name = findUser name >>= userProfile >>= \p -> Just (profileAge p)

With do-notation — looks imperative but is just sugar for >>=:

lookupAge :: String -> Maybe Int
lookupAge name = do
    user <- findUser name
    profile <- userProfile user
    return (profileAge profile)

If any step returns Nothing, the whole thing is Nothing. The <- extracts the value if Just; do-notation handles the threading.

return wraps a value into the monad — for Maybe, return x = Just x. Despite the name, this isn't a control-flow return; it's just a name for Just (or any monad's wrap-pure).

Available helpers:

import Data.Maybe

fromMaybe 0 (Just 5)            -- 5
fromMaybe 0 Nothing             -- 0
maybe "none" show (Just 5)      -- "5"
maybe "none" show Nothing       -- "none"
isJust, isNothing
catMaybes [Just 1, Nothing, Just 2]   -- [1, 2]

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…