Given a sequence of eithers Seq[Either[String,A]] with Left being an error message. I want to obtain an Either[String,Seq[A]] where I
I'm not used to use Either - here is my approach; maybe there are more elegant solutions:
def condense [A] (sesa: Seq [Either [String, A]]): Either [String, Seq [A]] = {
val l = sesa.find (e => e.isLeft)
if (l == None) Right (sesa.map (e => e.right.get))
else Left (l.get.left.get)
}
condense (List (Right (3), Right (4), Left ("missing"), Right (2)))
// Either[String,Seq[Int]] = Left(missing)
condense (List (Right (3), Right (4), Right (1), Right (2)))
// Either[String,Seq[Int]] = Right(List(3, 4, 1, 2))
Left (l.get.left.get) looks a bit funny, but l itself is a Either [A, B], not an Either [A, Seq[B]], and needs rewrapping.