gpt4 book ai didi

haskell - 在do block 中具有不同Left的Chain ExceptT

转载 作者:行者123 更新时间:2023-12-03 08:50:36 24 4
gpt4 key购买 nike

我要运行一些计算,这些计算会引发不同种类的异常。我如何将它们链接在do块中而不评估每一个,然后将结果匹配为Either ex result

type IntComp ex = ExceptT ex IO Int

local :: IntComp IOException
local = ExceptT $ map length <$> tryIO (readFile "file")

web :: IntComp WebException
web = ExceptT $ map length <$> tryAny (getWebsite "file")

comp :: (Exception ex) => IntComp ? -> IntComp ? -> IntComp ?
comp local web = ExceptT $ do
res1 <- local
res2 <- web
return (res1 + res2)

由于它们都有一个 Exception实例,所以我认为必须有某种方法可以类似方式编写 comp函数吗?

最佳答案

如果您有两种异常类型EOneETwo,则可以这样进行:

twoExceptions :: ExceptT (Either EOne ETwo) m a
twoExceptions = do
fmapL Left computationThatFailsWithEOne -- :: ExceptT EOne m b
fmapL Right computationThatFailsWithETwo -- :: ExceptT ETwo m c
...

关于haskell - 在do block 中具有不同Left的Chain ExceptT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935616/

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