I wrote a function of type Seq[Either[String,Int]] => Either[String, Seq[Int]]scala> xsres11: List[Either[String,Int]] = List(Right(1), Right(55))scala> accres12: Either[String,Seq[Int]] = Right(List())scala> xs.foldLeft(acc){ (acc, elem) => {     |     acc.right.flatMap(list => elem.right.map(_ +: list) )     | }}res10: Either[String,Seq[Int]] = Right(List(55, 1))Please review my foldLeft solution. Perhaps there's a higher order function that can more elegantly do this work?
Seq[Either[A, B]] => Either[A, Seq[B]] Function
scala
A few points:Your implementation reverses the order of elements if it succeeds (i.e. if they're all rights). I'm assuming this isn't intentional?You're taking a list but returning a Seq. This may be what you want, but I find it a little confusing.The inner curly brackets are unnecessary (and I personally find them kind of noisy).I'd strongly suggest not shadowing the external acc with the accumulator function argument.So I'd probably write it like this:val xs: List[Either[String, Int]] = List(Right(1), Right(55))xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>  acc.right.flatMap(list => elem.right.map(_ :: list))}Or:xs.foldRight(Right(Nil): Either[String, List[Int]]) { (elem, acc) =>  for {    t <- acc.right    h <- elem.right  } yield h :: t}But that's only if I couldn't use cats or Scalaz, both of which provide this operation as sequenceU:scala> import cats._, cats.syntax.traverse._, cats.std.all._import cats._import cats.syntax.traverse._import cats.std.all._scala> val xs: List[Either[String, Int]] = List(Right(1), Right(55))xs: List[Either[String,Int]] = List(Right(1), Right(55))scala> xs.sequenceUres0: scala.util.Either[String,List[Int]] = Right(List(1, 55))Which is much nicer.