Accepted answer

You are looking for the scan combinator.

List(1,4,5,6,6,7,9).scanLeft(0)(_ + _)
res1: List[Int] = List(0, 1, 5, 10, 16, 22, 29, 38)

Remove the leading element with tail if you want I am not aware of a version of scan that does not take an initial value. The complexity is O(n) for this guy and you could implement it yourself with folding the list via an accumulator and a list (that contains past accumulators). The latter you take as a result.


@uberwatch's answer is the right one, but for the sake of completeness, here's the more "generic" functional solution using foldLeft:

val xs = Vector(1,4,5,6,6,7,9)
val (sumList, sum) = 
  xs.foldLeft((Vector.empty[Int], 0)) {
    case ((list, total), x) => 
      val newTotal = x + total
      (list :+ newTotal, newTotal) 
// sumList: Vector(1, 5, 10, 16, 22, 29, 38)
// sum: Int = 38

Related Query

More Query from same tag