How to reduce Seq[Either[A,B]] to Either[A,Seq[B]]?

前端 未结 8 1386
孤城傲影
孤城傲影 2020-12-05 01:31

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

8条回答
  •  日久生厌
    2020-12-05 02:17

    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.

提交回复
热议问题