Scala 中的运行总和流 [英] Stream of running sums in Scala
本文介绍了Scala 中的运行总和流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我上一个问题的后续.
给定函数 add_stream(s1:Stream[Int], s2:Stream[Int]):Stream[Int]
我想编码 running_sums(s:Stream[Int]):Stream[Int]
,它返回一个新的流:s1, s1 + s2, s1 + s2 + s3, ...
This is a follow-up to my previous question.
Given function add_stream(s1:Stream[Int], s2:Stream[Int]):Stream[Int]
I would like to code running_sums(s:Stream[Int]):Stream[Int]
, which returns a new stream : s1, s1 + s2, s1 + s2 + s3, ...
我可以想到以下实现,但如果 s
为空,则它不起作用
I can think of the following implementation but it does not work if s
is empty
def running_sums(s:Stream[Int]):Stream[Int] =
Stream.cons(s.head, add_streams(s.tail, running_sums(s)))
我可以按如下方式修复它:
I can fix it as follows:
def running_sums(s:Stream[Int]):Stream[Int] =
if (s.isEmpty) empty
else Stream.cons(s.head, add_streams(s.tail, running_sums(s)))
但是它看起来并不优雅.
However it does not look elegant.
您将如何实现 running_sums
?
推荐答案
有一个类似这样的库调用,叫做 scanLeft
There's a library call for something like this, called scanLeft
s.scanLeft(0)(_+_).tail
这篇关于Scala 中的运行总和流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文