Implementing Fibonacci sequence with infinite lists in Scala

I’m trying to create a Fibonacci sequence using Scala’s streams. Here’s my attempt:

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

When I try to print the first 10 elements, I get a StackOverflowError. It seems like the zipped method isn’t playing nice with streams.

fibSeq.take(10).foreach(println)
// Output:
// 0
// 1
// StackOverflowError

Does anyone know why this isn’t working as expected? Is there a better way to implement an infinite Fibonacci sequence in Scala? I’d appreciate any insights or alternative approaches.

I’ve encountered this issue before while working on a data analysis project that required Fibonacci sequences. Your approach is close, but the recursive nature is causing the stack overflow. Here’s a more memory-efficient solution I’ve used:

lazy val fibSeq: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibSeq.zip(fibSeq.tail).map(p => p._1 + p._2)

This uses zip and map, which work better with infinite streams. I also switched to BigInt to handle larger numbers. This should solve your StackOverflowError and allow you to generate as many Fibonacci numbers as you need.

To test, try:
fibSeq.take(10).toList

This should give you the first 10 Fibonacci numbers without any errors.

I’ve dealt with this issue before when working on a project that required generating large Fibonacci sequences. The problem with your current approach is that it’s causing excessive recursion, leading to the StackOverflowError.

Instead of using zipped, I found success with a slightly different approach:

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

This method uses zip and map, which are more efficient for infinite streams. Also, I switched to BigInt to handle larger Fibonacci numbers without overflow.

When you run fibSeq.take(10).foreach(println), you should get the first 10 Fibonacci numbers without any errors. This approach has worked well for me in production code where I needed to generate and work with large Fibonacci sequences efficiently.

hey flyingstar, i had a similar issue. try using zipwith instead of zipped.map. it’s more efficient for streams. heres wat worked for me:

lazy val fibSeq: Stream[Int] = 0 #:: fibSeq.scanLeft(1)(_ + _)

this should avoid the stackoverflowerror. lemme kno if it helps!