In Martin Odersky’s book “Programming in Scala” there is an example of computing the Fibonacci sequence starting with 2 numbers passed as arguments to the function fibFrom.
def fibFrom(a: Int, b: Int): Stream[Int] =
a #:: fibFrom(b, a + b)
If you apply the method take() to this recursive function like:
fibFrom(1, 1).take(15).print
The output will be:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, empty
Maybe this output is obvious for more experienced people, but I don’t understand how exactly this method take() makes the stream to be calculated further. Is 15 somehow nonobviously passed into fibFrom()?




With
you created Stream object, and that object has head which is Int and tail which is function. Take is function of Stream that will calculate 15 elements using tail and head. You can check source code of take() function: