斯卡拉:产生折叠的中间结果 [英] Scala: Producing the intermediate results of a fold

查看:100
本文介绍了斯卡拉:产生折叠的中间结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了多次在整个地图操作中维护状态的问题。想象下面的任务:

给定一个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 fold )实际上是由 scan 生成的列表的最后一个元素。 code>)。



至于Scala,我会给出这个示例

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆