Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream of running sums in Scala

Tags:

stream

scala

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?

like image 352
Michael Avatar asked Dec 17 '22 06:12

Michael


2 Answers

There's a library call for something like this, called scanLeft

s.scanLeft(0)(_+_).tail
like image 108
Dave Griffith Avatar answered Jan 01 '23 20:01

Dave Griffith


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)
like image 20
Heiko Seeberger Avatar answered Jan 01 '23 22:01

Heiko Seeberger