ContT 和 ErrorT 都允许非标准控制流。有一种方法可以在 mtl 中将 ErrorT 类型包装在 ContT 周围:
instance (Error e, MonadCont m) => MonadCont (ErrorT e m)
但是这两个单子变压器不通勤。记住:
newtype Identity a = Identity {runIdentity :: a}
newtype ErrorT e m a = ErrorT {runErrorT :: m (Either e a)}
newtype ContT r m a = ContT {runContT :: (a -> m r) -> m r}
ErrorT String (ContT Bool Identity) ()
在 mtl 包中没问题的可能是:
ErrorT (ContT ( \ (k :: Either String () -> Identity Bool) -> k (Right ()) ) )
ContT r (ErrorT e Identity) a
在 mtl 包中不行。但是你可以写。
您想要在组合单子中的 (>>=) 语义是什么?您希望您的嵌套错误处理程序堆栈如何与非本地 callCC 交互?
以下是我的写法:
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances #-}
import Control.Monad
import Control.Monad.Cont
import Control.Monad.Error
import Data.Function
import Data.IORef
handleError :: MonadError e m => (e -> m a) -> m a -> m a
handleError = flip catchError
test2 :: ErrorT String (ContT () IO) ()
test2 = handleError (\e -> throwError (e ++ ":top")) $ do
x <- liftIO $ newIORef 1
label <- callCC (return . fix)
v <- liftIO (readIORef x)
liftIO (print v)
handleError (\e -> throwError (e ++ ":middle")) $ do
when (v==4) $ do
throwError "ouch"
when (v < 10) $ do
liftIO (writeIORef x (succ v))
handleError (\e -> throwError (e ++ ":" ++ show v)) label
liftIO $ print "done"
go2 = runContT (runErrorT test2) (either error return)
{-
*Main> go2
1
2
3
4
*** Exception: ouch:middle:top
-}
所以上面只适用于 mtl,这是新实例及其工作原理:
instance MonadError e m => MonadError e (ContT r m) where
throwError = lift . throwError
catchError op h = ContT $ \k -> catchError (runContT op k) (\e -> runContT (h e) k)
test3 :: ContT () (ErrorT String IO) ()
test3 = handleError (\e -> throwError (e ++ ":top")) $ do
x <- liftIO $ newIORef 1
label <- callCC (return . fix)
v <- liftIO (readIORef x)
liftIO (print v)
handleError (\e -> throwError (e ++ ":middle")) $ do
when (v==4) $ do
throwError "ouch"
when (v < 10) $ do
liftIO (writeIORef x (succ v))
handleError (\e -> throwError (e ++ ":" ++ show v)) label
liftIO $ print "done"
go3 = runErrorT (runContT test3 return)
{-
*Main> go3
1
2
3
4
Left "ouch:middle:3:middle:2:middle:1:middle:top"
-}