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

前端 未结 8 1387
孤城傲影
孤城傲影 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:28

    Building on Kevin's solution, and stealing a bit from Haskell's Either type, you can create a method partitionEithers like so:

    def partitionEithers[A, B](es: Seq[Either[A, B]]): (Seq[A], Seq[B]) =
      es.foldRight (Seq.empty[A], Seq.empty[B]) { case (e, (as, bs)) =>
        e.fold (a => (a +: as, bs), b => (as, b +: bs))
      }
    

    And use that to build your solution

    def unroll[A, B](es: Seq[Either[A, B]]): Either[Seq[A], Seq[B]] = {
      val (as, bs) = partitionEithers(es)
      if (!as.isEmpty) Left(as) else Right(bs)
    }
    

提交回复
热议问题