Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to write firstRightOrLefts in Haskell?

Tags:

haskell

either

I have the following method:

firstRightOrLefts :: [Either b a] -> Either [b] a
firstRightOrLefts eithers = 
   case partitionEithers eithers of
      (_,  (x : _)) -> Right x
      (xs, _)       -> Left xs

What bothers me is the ugly pattern matching and I was wondering if there was a more idiomatic way to write this method. The idea is that I have a bunch of computations that can return Eithers and I just want to get the first result or all of the error messages. Maybe I'm using the wrong data structure. Maybe the Writer monad would be better suited to this task. I'm really not sure at this point. Cheers for any help!

like image 230
Robert Massaioli Avatar asked Nov 05 '14 19:11

Robert Massaioli


1 Answers

The reverse convention is actually just the monad definition for Either and the definition for sequence is adequate for this:

ghci> :t sequence :: [Either a b] -> Either a [b]
sequence :: [Either a b] -> Either a [b]
  :: [Either a b] -> Either a [b]

To actually apply this to your case we'd therefore need a function flipEither:

firstRightOrLefts = fe . sequence . map fe
    where fe (Left a) = Right a
          fe (Right b) = Left b
like image 174
CR Drost Avatar answered Sep 28 '22 17:09

CR Drost