gpt4 book ai didi

haskell - 处理 `ExceptT` 计算中的不同错误类型

转载 作者:行者123 更新时间:2023-12-03 07:44:21 25 4
gpt4 key购买 nike

(这个问题类似于this question,但是那个问题只收到了推荐errors包的评论,我想知道更多细节。)

我正在开发一个程序,该程序使用两个不同的包,它们都返回类型 IO (Either e a)Either e a。然而,e 在库之间是不一样的。

我想知道如何构建使用这两个库的函数。我应该使用 errors 的提示让我想到了 hushnote,但这感觉不太对:

data MyError = Error1 | Error2 | Error3

f :: IO (Either MyErrorType Text)
f = do
now <- someIoAction

runExceptT $ do
x <- note Error1 $ hush LibraryA.f
y <- ExceptT $ note Error2 . hush <$> LibraryB.IO.f
z <- ExceptT $ note Error3 . hush <$> LibraryB.IO.g
pure (x, y, z)

这样的代码应该如何构造?我应该匹配结果并转换错误类型吗? errors 包中还有什么我应该知道的吗?如果能回答关于如何像上面那样构建代码的(有点)具体问题,以及处理 Haskell 中非统一错误的一般指示,我将非常感激。

最佳答案

如果您只想处理一次错误,我会将 IO (Either ea) 转换为 IO a,并使用如下实用函数:

throwWhenLeft :: Exception e => IO (Either e a) -> IO a
throwWhenLeft io = either throwIO return =<< io

乍一看这看起来很危险,但在某些情况下(非常常见,IMO)它很有用:

  • 您必须处理由 IO a 或某些 Either e a 抛出/返回的各种异常。
  • 异常处理程序所做的几乎总是相同的。

关于haskell - 处理 `ExceptT` 计算中的不同错误类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937430/

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