There is a good example in Stream document that gets fibonacci numbers.
val fibs:Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
I would like to implement that by using sliding, so I tried followings.
val test = 0 #:: 1 #:: Stream.empty
test.sliding(2).map(_.sum).toStream
Last line correctly gets Stream(1, ?) but when I concatenate that to above as follows, I get a error (possibly stack overflow, I could not see the exact error message because it was too long) when I try to get 3rd member.
val fibs2:Stream[Int] = 0 #:: 1 #:: fibs2.sliding(2).map(_.sum).toStream
If I give 3 numbers as follows, it calculates sums of preceding two numbers. But that's not fibonacci number.
val fibs3:Stream[Int] = 0 #:: 0 #:: 1 #:: fibs3.sliding(2).map(_.sum).toStream
Any ideas or help would be appreciated.
Updates
- I doubt the cause of the error is that sliding method returns Iterator, which needs to know if next value is available using hasNext method
- sliding method should calculate any sum of previous n numbers if first seeders are given, which are called tribonacci (n=3), tetranacci (n=4), etc.