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