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

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

    Scala 2.8 has the methods scanLeft and scanRight which do exactly that.

    For 2.7 you can define your own scanLeft like this:

    def scanLeft[a,b](xs:Iterable[a])(s:b)(f : (b,a) => b) =
      xs.foldLeft(List(s))( (acc,x) => f(acc(0), x) :: acc).reverse
    

    And then use it like this:

    scala> scanLeft(List(1,2,3))(0)(_+_)
    res1: List[Int] = List(0, 1, 3, 6)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题