This is a follow-up to my previous question.
Given function add_stream(s1:Stream[Int], s2:Stream[Int]):Stream[Int]
I would like to code running_sums(s:Stream[Int]):Stream[Int]
, which returns a new stream : s1, s1 + s2, s1 + s2 + s3, ...
I can think of the following implementation but it does not work if s
is empty
def running_sums(s:Stream[Int]):Stream[Int] = Stream.cons(s.head, add_streams(s.tail, running_sums(s)))
I can fix it as follows:
def running_sums(s:Stream[Int]):Stream[Int] = if (s.isEmpty) empty else Stream.cons(s.head, add_streams(s.tail, running_sums(s)))
However it does not look elegant.
How would you implement running_sums
?
There's a library call for something like this, called scanLeft
s.scanLeft(0)(_+_).tail
What about scanLeft
?
scala> val sums = stream.scanLeft(List(0))((ns, n) => ns :+ (ns.last + n))
sums: scala.collection.immutable.Stream[List[Int]] = Stream(List(0), ?)
scala> sums take 5 foreach println
List(0)
List(0, 1)
List(0, 1, 3)
List(0, 1, 3, 6)
List(0, 1, 3, 6, 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With