Is there a name for the function defined as follows:
f :: [Either a b] -> Either [a] [b]
f x = let (y1, y2) = partitionEithers x in
case y1 of
[] -> Right y2
_ -> Left y1
Basically if the list contains at least on Left
it returns all the Left
s otherwise it returns all the Right
s.
Alternatively, are there some generalisation of this function over a type class that I've missed?
This is (almost) sequence
for Validation
; you just need to convert your a
s to [a]
s. So:
traverse (eitherToValidation . first pure)
If you rewrite your producer to produce Validation
s instead of Either
s in the first place it will be even less noisy.
Well certainly you can get a single Left or the Right using the either monad:
Prelude> let a = [Right "hello", Right "World", Right "Bye"]
Prelude> sequence a
Right ["hello","World","Bye"]
Prelude> let a = [Right "hello", Right "World", Left "Bye"]
Prelude> sequence a
Left "Bye"
But to get all the Left
values doesn't seem like anything in the base or common libraries I know so you're probably left rolling your own solution. That said, I think we can find a much more readable solution. I propose:
f x | any isLeft x = lefts x
| otherwise = rights x
or
f x | not (null ls) = ls
| otherwise = rs
where (ls,rs) = partitionEithers x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With