Sequence-like function which reports all the errors

Viewed 517

I'm looking for a function in the standard library with a signature similar to this one:

Traversable f => f (Either e a) -> Either [e] (f a)

Or maybe something like this:

(Traversable f, Monoid e) => f (Either e a) -> Either e (f a)

The idea is to collect the errors instead of failing when the first error is encountered.

I saw that my function looked very much like sequence and I was hoping that there was already a typeclass that modelled this pattern.

1 Answers

You can use the Validation data type for that. From the documentation:

[A] Validation is either a value of the type err or a, similar to Either. However, the Applicative instance for Validation accumulates errors using a Semigroup on err. In contrast, the Applicative for Either returns only the first error.

E.g.:

> sequenceA [Failure [1], Success "Test", Failure [2] :: Validation [Int] String]
Failure [1, 2]
Related