15

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.

2
  • haskell noob here, what does => mean? Commented Jun 11, 2021 at 23:43
  • @NooneAtAll It separates a context from the rest of the type. See haskell.org/tutorial/classes.html for more details. Commented Jun 12, 2021 at 1:12

1 Answer 1

19

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this seems like the way Either's Applicative ought to work, to match Const and refuse to throw away any information (unless the type tells it to). It's an old decision, I hope we'd know better today...
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.