我正在尝试构建一个 MaybeT-Transformer Monad,基于Real World Haskell中的示例,Chapter Monad Transformers:
data MaybeT m a = MaybeT { runMT :: m (Maybe a) }
instance (Monad m) => Monad (MaybeT m) where
m >>= f = MaybeT $ do a <- runMT m
case a of
Just x -> runMT (f x)
Nothing -> return Nothing
return a = MaybeT $ return (Just a)
instance MonadTrans MaybeT where
lift m = MaybeT $ do
a <- m
return (Just a)
这很好用,但现在我想让 MaybeT 成为 MonadWriter 的一个实例:
instance (MonadWriter w m) => MonadWriter w (MaybeT m) where
tell = lift . tell
listen m = MaybeT $ do unwrapped <- listen (runMT m)
return (Just unwrapped)
告诉是好的,但我无法正确使用监听功能。在构造函数折纸的 1 1/2 天后,我能想到的最好的就是你在上面看到的那个:unwrapped应该是 (Maybe a, w) 的元组,我想用 Maybe-Type 包装起来并将整个东西放在一个空的 MonadWriter 中。
但是编译器抱怨:
Occurs check: cannot construct the infinite type: a = Maybe a
When generalising the type(s) for `listen'
In the instance declaration for `MonadWriter w (MaybeT m)'
我错过了什么?