是否可以在 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
结合起来。
ExceptT
的 MonadPlus
实例具有相关但不相同的行为:它返回第一个成功(如果有)或错误列表:
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/