我正在尝试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

相当于MaybeTNothing的扩展似乎是MaybeT $ return Nothing,这有点冗长,而我不得不明确使用MaybeT构造函数对我来说是意外的。

Nothing monad中写MaybeT有更短/更清晰的方法吗?

最佳答案

灵感来自@luqui的评论

要在纯Nothing单声道中表现为MaybemaybeTNothing应该满足以下等式

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

10-07 17:51