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.sequenceU
res0: scala.util.Either[String,List[Int]] = Right(List(1, 55))
Which is much nicer.
def
in there. It seems you've demonstrated the execution sequence which could be rewritten as a function. Why not write up the actual function properly? \$\endgroup\$