Here is a Scala stream to calculate the Fibonacci sequence :
import scala.math.BigInt
object fib extends App {
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(
fibs.tail).map(n => {
n._1 + n._2
})
}
fibs take 5 foreach println
fibs take 6 foreach println
src : http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stream
Instead of taking the first n numbers in the sequence how to sum the first n numbers using a stream , and return this sum ?
I could introduce a var sum
like this :
object fib extends App {
var sum = 3;
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map(n => {
sum = n._1.toInt + n._2.toInt
n._1 + n._2
})
fibs take 5 foreach println
}
And then somehow check this summed value. But this is not a good solution.
Update : I'm attempting to provide the summed value and return values that compute this sum, not sum the actual stream.
So takeSum(7)
will return '0,1,1,2,3'
Assumption is that the n value sum will contain a subset of the fib sequence