报告所有错误的类似序列的函数
我正在标准库中寻找一个函数,其签名与此类似:
Traversable f => f (Either e a) -> Either [e] (f a)
或者可能是这样的:
(Traversable f, Monoid e) => f (Either e a) -> Either e (f a)
这个想法是收集错误而不是在遇到第一个错误时失败。
我看到我的函数看起来很像sequence,我希望已经有一个类型类来建模这种模式。
回答
您可以Validation为此使用数据类型。从文档:
[A]
Validation是任一类型的值err或a,类似Either。但是,Applicative实例 for使用onValidation累积错误。相反,for只返回第一个错误。SemigrouperrApplicativeEither
例如:
> sequenceA [Failure [1], Success "Test", Failure [2] :: Validation [Int] String]
Failure [1, 2]
- @luqui a problem is that the monad laws prescribe that the monadic `ap` (`p >>= f -> q >>= x -> return (f x)`) must be the same as `<*>`. But that is not compatible with this accumulating behavior of the errors. So `Validation` is not actually an instance of `Monad`.