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

前端 未结 8 1138
南笙
南笙 2020-12-10 11:01

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] = eit         


        
8条回答
  •  旧巷少年郎
    2020-12-10 11:26

    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)) }
    

提交回复
热议问题