haskell - 使用 ErrorT 累积错误

标签 haskell exception monads either

是否可以在 ErrorT monad 中累积错误消息?我想积累更多的错误。

最佳答案

您可以使用Control.Applicative.Lift中的Errors应用程序来自变形金刚:

ghci> import Control.Applicative
ghci> import Control.Applicative.Lift
ghci> failure ['a'] *> pure () <* failure ['b']
Other (Constant "ab")

它返回错误列表(如果有)或成功结果。

这种类型通常称为“验证”应用程序。有other implementations Hackage 上提供了其中的内容。一项可能的改进是放宽对故障容器为 Monoid 的要求,同时允许使用 Semigroup

请注意,Errors 类型不是 Monad。但您可以使用 Data.Functor.Compose 将其与其他 Applicative 结合起来。

<小时/>

ExceptTMonadPlus 实例具有相关但不相同的行为:它返回第一个成功(如果有)或错误列表:

ghci> throwE ['a'] `mplus` return () `mplus` throwE ['b'] :: ExceptT [Char] Identity ()
ExceptT (Identity (Right ()))
ghci> throwE ['a'] `mplus` throwE ['b'] :: ExceptT [Char] Identity ()
ExceptT (Identity (Left "ab"))

关于haskell - 使用 ErrorT 累积错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427855/

相关文章:

haskell - 为什么这个 Haskell 代码使用fundeps 进行类型检查,但对类型族产生不可触碰的错误?

haskell - 数据定义错误haskell

java - 没有声明抛出异常的魔法异常抛出器

python - 未满足前提条件的正确异常(exception)是什么?

haskell - 接口(interface)抽象设计

Haskell - getLine 在 putStr 之前调用

haskell - 如何处理嵌套条件

c++ - 尝试抛出异常处理

f# - 计算表达式不执行 Let

haskell 埃森 : How to get value out of Parser in IO monad