The method you need to use is
partition
, not span
:scala> (1 to 10).partition(_ % 2 == 0)
res0: (IndexedSeq[Int], IndexedSeq[Int]) = (Vector(2, 4, 6, 8, 10),Vector(1, 3, 5, 7, 9))
Since you want a
List[List[Int]]
, you could do this:val lst = (1 to 10).toList
val (evens, odds) = lst.partition(_ % 2 == 0)
val newList = List(evens,odds) // List(List(2, 4, 6, 8, 10), List(1, 3, 5, 7, 9))
The
span
method can only be used to split a sequence at a single point:scala> (1 to 10).span(_ < 5)
res1: (Range, Range) = (Range(1, 2, 3, 4),Range(5, 6, 7, 8, 9, 10))
When you tried
lst.span(_ % 2 == 0)
, the program found that the first item, 1, did not pass the test (_ % 2 == 0
), so all the elements were put in the second list, leaving none in the first.
No comments:
Post a Comment