1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

How do I force the evaluation to fibonacci immediately? Instead why def fibonacci(first : Int, second : Int) : Stream[Int] = first #:: fibonacci(second, first + second) works?
Whenever you call a function it gets evaluated immediately. So in your example you are calling the fibonacci method which will immediately call the fibonacci method which will immediately ... And so on. If you instead used the continually method to create the stream you would only do recursive methods when you needed. So, when the take in your example is called, your stream will calculate the needed values (1).
As for the other example, #:: is like the :: (cons) operator for lists, but that uses lazy evaluation (see the => in the constructor argument - just like in the continually method). Meaning, that the next call to fibonacci will only evaluate when needed, just as it happens with continually.
I would say ++ forces the evaluation of the recursive call, as the argument is by value. Which is quite unfortunate for streams, but it looks like it comes with inheritance in the collection library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.