val l: List[Int] = List(-12, 2, -2, -3, 4, 5, 6) val positiveList = l.filter(x => x > 0) val negativeList = l.filterNot(x => x > 0)
The list function partition combines both of these operations into a single traversal of the original list and returns two lists, one list of values where the predicate holds true and another list of values where the predicate does not hold true.
val l: List[Int] = List(-12, 2, -2, -3, 4, 5, 6) val positiveAndNegativeLists = l.partition(x => x > 0)
We can then access each list using positiveAndNegativeLists._1 and positiveAndNegativeLists._2, where the former is the list of all elements where the predicate is true and the latter contains all elements where the predicate is false.
for (y <- positiveAndNegativeLists._1) println(y) for (y <- positiveAndNegativeLists._2) println(y)
No comments:
Post a Comment