ekinrf
ekinrf

Reputation: 59

Why stack overflow error with this Scala code?

I wrote some awkward Fibonacci implementation just to test out Stream

def fibonacci(a : Int, b : Int) : Stream[Int] = Stream(a, b) ++ fibonacci(a + b, a + b * 2)

I know this is not the best implementation but couldn't figure out why this would stack overflow on any call to it, say fibonacci(0, 1) take(1)?

Thanks.

Upvotes: 1

Views: 117

Answers (1)

Jens Egholm
Jens Egholm

Reputation: 2710

Because you force the evaluation to the recursive fibonacci call immediately.

In other words you need to create a lazy generator instead, either by using a method such as continually or by mapping on the tail. Scaladoc actually have a good example for how to create a fibonacci stream here: http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream

Upvotes: 2

Related Questions