Scalas (a, b) .zipped (or Tuple2.zipped) concept using streams / infinite lists

here is what i thought would be the correct and useful definition of nums fibonacci in scala:

lazy val fibs:Stream[Int] = 0 #:: 1 #:: (fibs,fibs.tail).zipped.map(_+_) 

However, I get the following error:

 fibs take 10 foreach println 0 1 java.lang.StackOverflowError at scala.collection.mutable.LazyBuilder.(LazyBuilder.scala:25) at scala.collection.immutable.Stream$StreamBuilder.(Stream.scala:492) at scala.collection.immutable.Stream$.newBuilder(Stream.scala:483) at... 

I think zipped is not working correctly with threads? Any suggestions on how to make this work, or why it doesn't work (shouldn't?)?

+6
list scala stream infinite fibonacci
source share
2 answers

Works correctly

 val fibs:Stream[Int] = 0 #:: 1 #:: (fibs zip fibs.tail).map{ case (a,b) => a+b } 

The problem with Tuple2.zipped is that it assumes that it can run foreach in the sequences it fastens. This is probably by design, since everything Stream.zip does is likely to give you poor performance for any Seq length with a finite length that is not List or Stream . (Since most data structures do not support the efficient implementation of tail .)


Stream.zip is essentially implemented as follows (although it does some things to make types more general). A.

 class Stream[A]{ def zip(other:Stream[B]) = (this.head, other.head) #:: (this.tail zip other.tail) } 
+8
source share

There is a ticket in the Scala Trac database: http://lampsvn.epfl.ch/trac/scala/ticket/2634

The ticket was closed as wontfix, but pay attention to Adrian: "Or are we missing something?" in the comments - perhaps this will someday be considered.

+3
source share

All Articles