作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个非常简单的抽象来处理一系列可以回滚的 IO 操作(在某种程度上),即如果一个操作写入一个文件,那么回滚将删除这个文件或者如果一个操作创建一个目录树,修剪这将是回滚等。
data IOAction = IOAction {
execute :: IO (),
rollback :: IO ()
}
executeAll :: [IOAction] -> IO ()
executeAll [] = return ()
executeAll (a : as) = do
execute a
executeAll as `catch` rollbackAndRethrow
where
rollbackAndRethrow :: SomeException -> IO ()
rollbackAndRethrow e = rollback a >> throw e
writeFilesAtomically :: CanRollbackT IO ()
writeFilesAtomically = do
a1 <- (writeFile a str1) `orRollback` removeFile a
a2 <- (writeFile x str2) `orRollback` removeFile x
....
最佳答案
这看起来很像 WriterT
monad 结合 ExceptT
.你可能会做这样的事情:
orRollback action rollaction = do
eres <- liftIO $ try action
case eres of
Right res -> do
tell [rollaction]
return res
Left (e :: SomeException) -> throwE e
runMyComputation computation = do
(res, rolls) <- runWriterT $ runExceptT $ computation
case res of
Right r -> return r
Left e -> do
sequence_ (reverse rolls) -- Handle errors in rollbacks?
throwIO e
[]
更好的幺半群如果您要经常看到异常。
onRollback
非 IO 操作。但这可能完全没问题。
关于haskell - 回滚 IO 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510611/
我是一名优秀的程序员,十分优秀!