I'm using Scala 2.13.1 and evaluate my examples in a worksheet.
At first, I define two functions that return the range of a to (z-1) as a stream or respectively a lazy list.
def streamRange(a: Int, z: Int): Stream[Int] = {
print(a + " ")
if (a >= z) Stream.empty else a #:: streamRange(a + 1, z)
}
def lazyListRange(a: Int, z: Int): LazyList[Int] = {
print(a + " ")
if (a >= z) LazyList.empty else a #:: lazyListRange(a + 1, z)
}
Then I call both functions, take a Stream/LazyList of 3 elements and convert them to List:
streamRange(1, 10).take(3).toList // prints 1 2 3
lazyListRange(1, 10).take(3).toList // prints 1 2 3 4
Here I do the same again:
val stream1 = streamRange(1, 10) // prints 1
val stream2 = stream1.take(3)
stream2.toList // prints 2 3
val lazyList1 = lazyListRange(1,10) // prints 1
val lazyList2 = lazyList1.take(3)
lazyList2.toList // prints 2 3 4
The 1 is printed because the function is visited and the print statement is at the start. No surprise.
But I don't understand why the additional 4 is printed for the lazy list and not for the stream.
My assumption is that at the point where 3 is to be concatenated with the next function call, the LazyList version visits the function, whereas in the Stream version the function is not visited. Otherwise the 4 would not have been printed.
It seems like unintended behaviour, at least it is unexpected. But would this difference in side effects be considered a bug or just a detailed difference in the evaluation of Stream and LazyList.