简体   繁体   中英

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?

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,...) (ie 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM