在 Scala 中,如何折叠 List 并返回中间结果? [英] In Scala, how do I fold a List and return the intermediate results?
本文介绍了在 Scala 中,如何折叠 List 并返回中间结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个月中的天数列表:
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:
val cumDays = List(31, 59, 90)
我想过使用折叠运算符:
I've thought of using the fold operator:
(0 /: days)(_ + _)
但这只会返回最终结果(365),而我需要中间结果列表.
but this will only return the final result (365), whereas I need the list of intermediate results.
无论如何我可以优雅地做到这一点?
Anyway I can do that elegantly?
推荐答案
Scala 2.8 有方法 scanLeft
和 scanRight
正是这样做的.
Scala 2.8 has the methods scanLeft
and scanRight
which do exactly that.
对于 2.7,您可以像这样定义自己的 scanLeft
:
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
然后像这样使用它:
scala> scanLeft(List(1,2,3))(0)(_+_)
res1: List[Int] = List(0, 1, 3, 6)
这篇关于在 Scala 中,如何折叠 List 并返回中间结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文