将 Scala Stream 转换为一个新的 Stream,它是当前元素和前一个元素的总和 [英] Transform a Scala Stream to a new Stream which is the sum of the current element and the previous element

查看:38
本文介绍了将 Scala Stream 转换为一个新的 Stream,它是当前元素和前一个元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换一个 Scala 整数流,以便我们有一个新的流,其中的元素是这个元素和前一个元素的总和.

How to transform a Scala Stream of integers so that we have a new Stream where the elements are the sum of this element and the previous element.

例如,如果输入流是 1, 2, 3, 4 ... 那么输出流是 1, 3, 5, 7.

By example if the input stream is 1, 2, 3, 4 ... then the output stream is 1, 3, 5, 7.

还有第二个问题,如何使总和使用输出流中的前一个,以便输出为 1, (2+(1)), (3+(2+1)), (4+(3+(2+1))).

Also a second question, how would you make the sum use the previous one in the output stream so that the output would be 1, (2+(1)), (3+(2+1)), (4+(3+(2+1))).

推荐答案

只需使用自身的移位版本压缩流并将两个元素相加即可.

Just zip your stream with a shifted version of itself and sum the two elements.

val s1 = Stream.from(0) // 0, 1, 2, 3, ...
val s2 = Stream.from(1) // 1, 2, 3, 4, ...
val sumOfTwo = s1.zip(s2).map{ case (a,b) => a+b } // 1, 3, 5, 7, ...

要计算总和,只需使用 scan 函数,它的作用类似于折叠,但在每一步都返回元素.

To compute the total sum, just use the scan function that acts like a fold but returning elements at each step.

val totalSum = s1.scan(0)((ctr, el) => ctr + el) // 0, 1, 3, 6, 10, ...

这篇关于将 Scala Stream 转换为一个新的 Stream,它是当前元素和前一个元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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