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

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

    Fold your list into a new list. On each iteration, append a value which is the sum of the head + the next input. Then reverse the entire thing.

    scala> val daysInMonths = List(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    daysInMonths: List[Int] = List(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    
    scala> daysInMonths.foldLeft(Nil: List[Int]) { (acc,next) => 
         | acc.firstOption.map(_+next).getOrElse(next) :: acc    
         | }.reverse                                             
    res1: List[Int] = List(31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
    

提交回复
热议问题