Reputation: 4673
Running:
lazy val s: Stream[Int] = 1 #:: 2 #:: {val x = s.tail.map(_+1); println("> " + x.head); x}
s.take(5).toList
I'd expect:
> List(2, 3)
> List(2, 3, 4)
List(1, 2, 3, 4, 5)
And I get:
> 3
List(1, 2, 3, 4, 5)
Could you explain it to me?
Upvotes: 5
Views: 333
Reputation: 370162
The reason that you're getting an Int
instead of a List
is that s
is a stream of integers, so it contains integers, not lists.
The reason why you get 3 is that the tail of (1,2,3,4,5,...) (i.e. s
) is (2,3,4,5,...) and if you map +1 over that, you will get (3,4,5,6,7,...) and the head of that is 3.
The reason why only one integer is printed is that the expression is only evaluated once to get the stream for the tail. After that only the stream returned by s.tail.map(_+1)
is evaluated (which doesn't contain any print statements).
Upvotes: 6