我正在尝试MaybeT
monad,特别是MaybeT 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
相当于
MaybeT
的Nothing
的扩展似乎是MaybeT $ return Nothing
,这有点冗长,而我不得不明确使用MaybeT
构造函数对我来说是意外的。在
Nothing
monad中写MaybeT
有更短/更清晰的方法吗? 最佳答案
灵感来自@luqui的评论
要在纯Nothing
单声道中表现为Maybe
,maybeTNothing
应该满足以下等式
maybeTNothing >>= f = maybeTNothing
v >> maybeTNothing = maybeTNothing
这正是
mzero
实例中的MonadPlus
对 MaybeT
的要求。这样我们就可以使用mzero
maybeTNothing = mzero
https://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#t:MonadPlus