The Maybe type is very nearly
the simplest instance of
Monad. It represents a computation
that might not produce a result:
-- file: ch14/Maybe.hs instance Monad Maybe where Just x >>= k = k x Nothing >>= _ = Nothing Just _ >> k = k Nothing >> _ = Nothing return x = Just x fail _ = Nothing
If, when we chain together a number of
computations over Maybe using
(>>), any of them returns
Nothing, we don’t evaluate any of the remaining computations.
Note, though, that the chain is not
completely short-circuited. Each
(>>) in the chain will still match a
Nothing on its left and produce a
Nothing on its right, all the way to the end.
It’s easy to forget this point: when a computation in the chain fails,
the subsequent production, chaining, and consumption of
Nothing values are cheap at runtime, but they’re not
A function suitable for executing the
Maybe monad is
maybe. (Remember that
“executing” a monad involves evaluating it and returning
a result that’s had the monad’s type wrapper removed.)
-- file: ch14/Maybe.hs maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x
Its first parameter is the value to
return if the result is
Nothing. The second is a function
to apply to a result wrapped in the
Just constructor; the
result of that application is then returned.
Since the Maybe type is so
simple, it’s about as common to simply pattern match on a
Maybe value as it is to call
maybe. Each one is more readable ...