Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Stream confusion

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?

like image 957
Etam Avatar asked Dec 15 '11 21:12

Etam


1 Answers

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).

like image 74
sepp2k Avatar answered Nov 09 '22 14:11

sepp2k