Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scala to accumulate elementwise sums [duplicate]

Tags:

scala

Possible Duplicate:
In Scala, how do I fold a List and return the intermediate results?

I am searching for a functional way of accumulating the elements of a SortedTree in the following way:

I want a list with containing the sums of all precursors (including the element itself) for all elements in the SortedTree.

For Exmaple:

SortedTree contains (0.4, 0.3, 0.2, 0.1, 0.05)

I want the list: (0,4. 0.7, 0. 9, 1, 1.05)

Any suggestions?

like image 632
peri4n Avatar asked Apr 10 '26 03:04

peri4n


1 Answers

There is no SortedTree in the standard library, but you just want scanLeft (assuming your type extends TraversableLike):

seq.scanLeft(0.0)(_ + _).tail

or if you want a list:

seq.toList.scanLeft(0.0)(_ + _).tail
like image 177
Alexey Romanov Avatar answered Apr 13 '26 09:04

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!