4

我正在尝试构建一个 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)'

我错过了什么?

4

1 回答 1

6

listen有类型签名

  m a -> m (a, w)

IE

 MaybeT m a -> MaybeT m (a, w)

MaybeT $ listen (runMT m) >>= return . Just有类型签名

 MaybeT m a -> MaybeT m (Maybe a, w)

因此引发了无限类型错误。您需要将其转换unwrapped :: (Maybe a, w)为 aMaybe (a, w)才能继续:

listen m = MaybeT $ do (val, wr) <- listen (runMT m)
                    case val of
                        Nothing -> return Nothing
                        Just x  -> return (Just (x, wr))

(顺便说一句,在http://www.haskell.org/haskellwiki/New_monads/MaybeT中有一个 MaybeT 的实现。)

于 2010-05-01T21:59:20.970 回答