斯卡拉:产生折叠的中间结果 [英] Scala: Producing the intermediate results of a fold
问题描述
我遇到了多次在整个地图操作中维护状态的问题。想象下面的任务:
给定一个List [Int],将每个元素映射到前面所有元素和它自身的总和。
So 1, 2,3变成1,1 + 2,1 + 2 + 3。
我提出的一个解决方案是:
scala> val a = 1到5
a:scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne =范围(1,2,3,4,5)
scala> a.foldLeft(List(0)){case(l,i)=> (l.head + i):: l} .reverse
res3:List [Int] = List(0,1,3,6,10,15)
但是不知何故,我觉得必须有一个更简单的解决方案。
计算这种累计的一般操作不是 fold
,而是 scan 可以通过<$ c $来表示,但 scan
scala> scanLeft(List(1,2,3))(0)(_ + _)
res1:List [Int] = List(0,1,3,6)
I've come across the problem of maintaining a state throughout a map operation several times. Imagine the following task:
Given a List[Int], map each element to the sum of all preceding elements and itself.
So 1,2,3 becomes 1, 1+2, 1+2+3.
One solution I've come up with is:
scala> val a = 1 to 5
a: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(1, 2, 3, 4, 5)
scala> a.foldLeft(List(0)){ case (l,i) => (l.head + i) :: l }.reverse
res3: List[Int] = List(0, 1, 3, 6, 10, 15)
But somehow I feel that there has to be a simpler solution.
You're trying to compute the sequence of partial sums.
The general operation for computing such accumulations is not fold
but scan
, though scan
is expressible through fold
in the way you showed (and fold
is actually the last element of the list produced by scan
).
As to Scala, I'll give this example
scala> scanLeft(List(1,2,3))(0)(_ + _)
res1: List[Int] = List(0, 1, 3, 6)
这篇关于斯卡拉:产生折叠的中间结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!