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
Run Code Online (Sandbox Code Playgroud)
Basically if the list contains at least on Left it returns all the Lefts otherwise it returns all the Rights.
Alternatively, are there some generalisation of this function over a type class that I've missed?
Dan*_*ner 11
This is (almost) sequence for Validation; you just need to convert your as to [a]s. So:
traverse (eitherToValidation . first pure)
Run Code Online (Sandbox Code Playgroud)
If you rewrite your producer to produce Validations instead of Eithers 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"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
or
f x | not (null ls) = ls
| otherwise = rs
where (ls,rs) = partitionEithers x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |