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

前端 未结 8 958
失恋的感觉
失恋的感觉 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)
    

提交回复
热议问题