Scala序列,每个元素代表所有前面元素的总和

Scala sequence, each element represents sum of all previous elements

我在 Scala 中有一个序列集合如下:

val DaysInMonths = Seq(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) 

我如何有效地将这个序列转换成这样的序列,其中每个元素代表前面元素的总和,如下所示:

  val DaysInMonths = Seq(31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) 

我有以下一种可行的解决方案:

DaysInMonths.zipWithIndex.foldLeft(Seq.empty[Int]) {
  case (Nil, (cur, _)) => Seq(cur)
  case (acc, (cur, 1)) if isLeapYear(year) => acc ++ Seq(acc.last + 29)
  case (acc, (cur, i)) => acc ++ Seq(acc.last + cur)
}

但由于我是 Scala 的新手,我想知道应该有更好和更短的方法来实现同样的目标。

您可以使用 scanLeft:

scala>   DaysInMonths.scanLeft(0)(_ + _)
res1: Seq[Int] = List(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)

注意是给序列加上初值,你可以决定是保留还是取尾忽略。