gpt4 book ai didi

haskell - 理解 `bracket`函数

转载 作者:行者123 更新时间:2023-12-05 00:14:25 25 4
gpt4 key购买 nike

看着bracket函数来自 Parallel and Concurrent Programming in Haskell :

bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket before after during = do
a <- before
c <- during a `onException` after a
after a
return c

如果发生异常,为什么 after函数只被调用一次?换句话说,我对 after a 的明显执行感到困惑。发生异常时两次。

但是,代码显示 after a据我了解,只被调用一次:
λ: >data MyException = MyException deriving Show
λ: >instance Exception MyException

λ: >let e = return MyException :: IO MyException

λ: >bracket e (const $ putStrLn "clean up!") return
clean up!
MyException

最佳答案

来自 the docs for bracket :

When you want to acquire a resource, do some work with it, and then release the resource, it is a good idea to use bracket, because bracket will install the necessary exception handler to release the resource in the event that an exception is raised during the computation. If an exception is raised, then bracket will re-raise the exception (after performing the release).



onException :

Like finally, but only performs the final action if there was an exception raised by the computation.



因此,如果 during a 抛出异常,第一次调用 after a执行,然后再次抛出异常,跳过第二个 after a ;如果没有异常,只执行第二个。

请注意,在您的示例代码中,您返回的是一个异常,而不是抛出它——要抛出它,您需要使用 throw或者最好是 throwIO :: Exception e => e -> IO a .

关于haskell - 理解 `bracket`函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com