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

前端 未结 8 953
失恋的感觉
失恋的感觉 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:52

    Works on 2.7.7:

    def stepSum (sums: List [Int], steps: List [Int]) : List [Int] = steps match { 
         case Nil => sums.reverse.tail                                                  
         case x :: xs => stepSum (sums.head + x :: sums, steps.tail) }
    
    days
    res10: List[Int] = List(31, 28, 31, 30, 31)
    
    stepSum (List (0), days) 
    res11: List[Int] = List(31, 59, 90, 120, 151)
    

提交回复
热议问题