Scala Current Amount Flow

This is a continuation of my previous question.
This 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 come up with the following implementation, but it does not work if s empty

  def running_sums (s: Stream [Int]): Stream [Int] =
   Stream.cons (s.head, add_streams (s.tail, running_sums (s))) 

I can fix it like this:

  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 ?

+4
source share
2 answers

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

 s.scanLeft(0)(_+_).tail 
+7
source

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) 
+5
source

Source: https://habr.com/ru/post/1385952/


All Articles