I am defining a stream in terms of itself (a recursive definition). When trying to access the second element of the stream, StackOverflowError
is thrown. The code from scala console:
scala> val s1 = Stream.iterate(1)(identity _)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> lazy val s2 : Stream[Int]= Stream.cons(1, (s2, s1).zipped.map { _ + _ })
s2: Stream[Int] = <lazy>
scala> s1 take 5 print
1, 1, 1, 1, 1, empty
scala> s2(0)
res4: Int = 1
scala> s2(1)
java.lang.StackOverflowError
at $anonfun$s2$1$$anonfun$apply$1.apply(<console>:9)
at $anonfun$s2$1$$anonfun$apply$1.apply(<console>:9)
at scala.Tuple2$Zipped$$anonfun$map$1.apply(Tuple2.scala:62)
at scala.collection.immutable.Stream.foreach(Stream.scala:255)
at scala.Tuple2$Zipped.map(Tuple2.scala:60)
at $anonfun$s2$1.apply(<console>:9)
at $anonfun$s2$1.apply(<console>:9)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:556)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:550)
at scala.collection.immutable.Stream.foreach(Stream.scala:256)
at scala.Tuple2$Zipped.map(Tuple2.scala:60)
at $anonfun$s2$1.apply(<console>:9)
at $anonfun$s2$1.apply(<console>:9)
at scala.collection.immutable.Stream$Cons.tail(Stream.scala:556)
at scala.collection.immutable.Str...
I am unable to understand the reason of the stack overflow. Since streams are inherently lazy, recursive mapping should work.
What is wrong with this scenario?
I am using Scala version 2.8.0.RC2.