Reputation: 9
Define the "split" function that divides a stream into two streams. The first list should contain elements with odd indexes and the second with even indexes. Example: split(Stream(5, 6, 3, 2, 1)) -> Stream(5, 3, 1) and Stream(6, 2)
My attempt:
def split(originalElements: Stream[Any]): (Stream[Any], Stream[Any]) = {
var oddList: Stream[Any] = Stream();
var evenList: Stream[Any] = Stream();
for (i <- 0 until originalElements.length) {
if (i % 2 == 0) {
oddList = oddList :+ originalElements(i)
} else {
evenList = evenList :+ originalElements(i)
}
}
(oddList, evenList)
}
println(split(Stream(5, 6, 3, 2, 1)))
I get this output -> (Stream(5, <not computed>),Stream(6, <not computed>))
I'm somehow confused in stream functions, could someone help me to understand what is wrong in this code and why I don't get the right output? Thank you in advance!
Upvotes: 0
Views: 146
Reputation: 763
You can try to use partitioning function or reimplement it with filter
and filterNot
functions by yourself. Stream isn't a list, you shouldn't use length
. Stream might be infinite.
val s = Stream(5, 6, 3, 2, 1)
val (oddStream, evenStream) = {
val (odd, even) = s.zipWithIndex.partition {
case (_, i) => i % 2 == 0
}
(odd.map(_._1), even.map(_._1))
}
Upvotes: 2