Search code examples
arraysscalaincrementaccumulator

Incrementing Variable in a foldLeft


I have Scala code like this

var i = 1
for(e <- array) {
    acc += e * i
    i += 1
}

I need to multiply the first element in the array by 1, the next by 2, the next by 3 and so on adding it all into an accumulator. I feel that there is a better way of doing this in Scala, maybe even with folding?


Solution

  • val x = List(1,1,1,1,1,1)
    (((0,1) /: x){case ((acc, mult), l) => (acc + (l * mult), mult + 1) })._1
    

    In other words, starting with an accumulator of 0 and a multiplier of 1, fold each element of the list in, changing the accumulator to acc + (l * mult) and incrementing the multiplier by 1. We get the final multiplier out at the end as well, so we call ._1 to just get the accumulator.

    Edit: As @RexKerr points in his answer below (and the comment), if performance is a major concern then you're better off using an explicit recursive method.