How to split a List[Either[A, B]]

心不动则不痛 提交于 2019-12-17 19:37:34

问题


I want to split a List[Either[A, B]] in two lists.

Is there a better way ?

def lefts[A, B](eithers : List[Either[A, B]]) : List[A] = eithers.collect { case Left(l) => l}
def rights[A, B](eithers : List[Either[A, B]]) : List[B] = eithers.collect { case Right(r) => r}

回答1:


Not sure this is really much neater, but :

scala> def splitEitherList[A,B](el: List[Either[A,B]]) = {
         val (lefts, rights) = el.partition(_.isLeft)
         (lefts.map(_.left.get), rights.map(_.right.get))
       }
splitEitherList: [A, B](el: List[Either[A,B]])(List[A], List[B])

scala> val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
el: List[Either[Int,String]] = List(Left(1), Right(Success), Left(42))

scala> val (leftValues, rightValues) = splitEitherList(el)
leftValues: List[Int] = List(1, 42)
rightValues: List[String] = List("Success")



回答2:


If scalaz is one of your dependencies I would simply use separate:

import scalaz.std.list._
import scalaz.std.either._
import scalaz.syntax.monadPlus._

val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))

scala> val (lefts, rights) = el.separate
lefts: List[Int] = List(1, 42)
rights: List[String] = List(Success)



回答3:


Starting Scala 2.13, most collections are now provided with a partitionMap method which partitions elements based on a function which returns either Right or Left.

In our case, we don't even need a function that transforms our input into Right or Left to define the partitioning as we already have Rights and Lefts. Thus a simple use of identity:

val (lefts, rights) = List(Right(2), Left("a"), Left("b")).partitionMap(identity)
// lefts: List[String] = List(a, b)
// rights: List[Int] = List(2)



回答4:


You can do it with:

val (lefts, rights) = eithers.foldRight((List[Int](), List[String]()))((e, p) => e.fold(l => (l :: p._1, p._2), r => (p._1, r :: p._2)))



回答5:


A compact, but not CPU-effictive solution:

val lefts = list.flatMap(_.left.toOption)
val rights = list.flatMap(_.right.toOption)



回答6:


Well, in case it doesn't have to be a one-liner... then it can be a no-brainer.

def split[A,B](eithers : List[Either[A, B]]):(List[A],List[B]) = {
  val lefts = scala.collection.mutable.ListBuffer[A]()
  val rights = scala.collection.mutable.ListBuffer[B]()
  eithers.map {
    case Left(l) => lefts += l
    case Right(r) => rights += r
  }
  (lefts.toList, rights.toList)
}

But, to be honest, I'd prefer Marth's answer :)




回答7:


If you're going to bother to abstract the functionality, as in Marth's answer, then it may actually make more sense to use roterl's solution:

def splitEitherList[A,B](el: List[Either[A,B]]): (List[A], List[B]) =
  (el :\ (List[A](), List[B]()))((e, p) =>
    e.fold(l => (l :: p._1, p._2), r => (p._1, r :: p._2)))

val x = List(Left(1), Right(3), Left(2), Left(4), Right(8))
splitEitherList(x) // (List(1, 2, 4), List(3, 8))

This way awards more functional brownie points, but also may be more performant, as it makes use of a right fold to create the lists in one pass

But if you're doing it on the fly and/or find folds difficult to read, then by all means

el.partition(_.isLeft) match { case (lefts, rights) =>
  (lefts.map(_.left.get), rights.map(_.right.get)) }



回答8:


A somewhat functional solution for Seq.

def partition[A, B](seq: Seq[Either[A, B]]): (Seq[A], Seq[B]) = {
  seq.foldLeft[(Seq[A], Seq[B])]((Nil, Nil)) { case ((ls, rs), next) =>
    next match {
      case Left(l) => (ls :+ l, rs)
      case Right(r) => (ls, rs :+ r)
    }
  }
}


来源:https://stackoverflow.com/questions/26576530/how-to-split-a-listeithera-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!