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

Viewed 12123

I've got a List of days in the month:

val days = List(31, 28, 31, ...)

I need to return a List with the cumulative sum of days:

val cumDays = List(31, 59, 90)

I've thought of using the fold operator:

(0 /: days)(_ + _)

but this will only return the final result (365), whereas I need the list of intermediate results.

Anyway I can do that elegantly?

8 Answers

For any:

val s:Seq[Int] = ...

You can use one of those:

s.tail.scanLeft(s.head)(_ + _)
s.scanLeft(0)(_ + _).tail

or folds proposed in other answers but... be aware that Landei's solution is tricky and you should avoid it.

BE AWARE

s.map { var s = 0; d => {s += d; s}} 
//works as long `s` is strict collection

val s2:Seq[Int] = s.view //still seen as Seq[Int]
s2.map { var s = 0; d => {s += d; s}} 
//makes really weird things! 
//Each value'll be different whenever you'll access it!

I should warn about this as a comment below Landei's answer but I couldn't :(.

Related