Nothing about MaybeT monad: a more concise way?
I am experimenting with monad MaybeT
, in particularMaybeT Identity String
import Control.Monad.Trans.Maybe
import Control.Monad.Identity
import Data.Maybe
main :: IO ()
main = putStrLn . show . runIdentity . runMaybeT $ maybeGetString
maybeGetString :: MaybeT Identity String
maybeGetString = return "first" >>
maybeTNothing >>
return "second"
maybeTNothing :: MaybeT Identity String
maybeTNothing = MaybeT $ return Nothing
The experiment for the equivalent MaybeT
Nothing
seems MaybeT $ return Nothing
to feel a bit verbose, and it seems surprising to me that I have to explicitly use the constructor MaybeT
.
Is there a shorter / more convenient / clearer way to write Nothing
in a monad MaybeT
?
source to share
Inspired by comment from @luqui
To behave as Nothing
in a simple monad Maybe
, maybeTNothing
must satisfy the equations
maybeTNothing >>= f = maybeTNothing
v >> maybeTNothing = maybeTNothing
These are exactly the requirements for mzero
from MonadPlus
, which MaybeT
is the instance. Therefore, we can simply usemzero
maybeTNothing = mzero
https://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#t:MonadPlus
source to share