SHARE
TWEET

Untitled

a guest Oct 12th, 2017 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def lefts[A, B](eithers : List[Either[A, B]]) : List[A] = eithers.collect { case Left(l) => l}
  2. def rights[A, B](eithers : List[Either[A, B]]) : List[B] = eithers.collect { case Right(r) => r}
  3.    
  4. scala> def splitEitherList[A,B](el: List[Either[A,B]]) = {
  5.          val (lefts, rights) = el.partition(_.isLeft)
  6.          (lefts.map(_.left.get), rights.map(_.right.get))
  7.        }
  8. splitEitherList: [A, B](el: List[Either[A,B]])(List[A], List[B])
  9.  
  10. scala> val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
  11. el: List[Either[Int,String]] = List(Left(1), Right(Success), Left(42))
  12.  
  13. scala> val (leftValues, rightValues) = splitEitherList(el)
  14. leftValues: List[Int] = List(1, 42)
  15. rightValues: List[String] = List("Success")
  16.    
  17. 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)))
  18.    
  19. import scalaz.std.list._
  20. import scalaz.std.either._
  21. import scalaz.syntax.monadPlus._
  22.  
  23. val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
  24.  
  25. scala> val (lefts, rights) = el.separate
  26. lefts: List[Int] = List(1, 42)
  27. rights: List[String] = List(Success)
  28.    
  29. val lefts = list.flatMap(_.left.toOption)
  30. val rights = list.flatMap(_.right.toOption)
  31.    
  32. def split[A,B](eithers : List[Either[A, B]]):(List[A],List[B]) = {
  33.   val lefts = scala.collection.mutable.ListBuffer[A]()
  34.   val rights = scala.collection.mutable.ListBuffer[B]()
  35.   eithers.map {
  36.     case Left(l) => lefts += l
  37.     case Right(r) => rights += r
  38.   }
  39.   (lefts.toList, rights.toList)
  40. }
RAW Paste Data
Top