I have a List[Int]
from 1 to 10 and want to make a List[List[Int]]
containing two List[Int]
: one list containing even numbers and the other containing odd numbers. The result should be like this:
List(List(2,4,6,8,10),List(1,3,5,7,9))
I tried these things:
1.to(10).toList.span((x:Int) => x % 2 == 0)
and
val lst = 1.to(10).toList; lst span (_%2==0)
However, neither of these worked.
Can someone help me on this matter?
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.