Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum list of integers and save each step to new list?

I'm struggling to find simple-functional way to transform

val ints = List(1, 2, 3, 4, 5) into List(1, 3, 6, 10, 15)

How can it be done?

like image 339
MaciejF Avatar asked Jan 25 '26 16:01

MaciejF


1 Answers

This operation is called prefix sum, cumulative sum, or inclusive scan, the more generalized higher-order function is usually called scan. Scala provides :A,That](z:B)(op:(B,B)=>B)(implicitcbf:scala.collection.generic.CanBuildFrom[Repr,B,That]):That">scan as part of its collections library:

ints.scan(0)(_ + _).tail
like image 74
Lee Avatar answered Jan 27 '26 04:01

Lee



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!