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

前端 未结 8 971
失恋的感觉
失恋的感觉 2020-12-08 07:12

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:

         


        
8条回答
  •  盖世英雄少女心
    2020-12-08 07:33

    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 :(.

提交回复
热议问题