【发布时间】:2013-07-25 20:25:45
【问题描述】:
我正在玩 Scala 的流,但我不确定我是否明白这个想法。 让我们考虑以下代码
def fun(s: Stream[Int]): Stream[Int] = Stream.cons(s.head, fun(s.tail))
执行这个
val f = fun(Stream.from(7))
f take 14 foreach println
结果
7 8 9 10 ... up to 20
假设我明白这一点。
现在,稍微改变一下代码(在头部添加 2)
def fun(s: Stream[Int]): Stream[Int] = Stream.cons(s.head + 2, fun(s.tail))
结果
9 10 11 ... up to 22
再次,我想我明白了。问题从下一个例子开始(d
def fun(s: Stream[Int]): Stream[Int] = Stream.cons(s.head / 2, fun(s.tail))
3 4 4 5 5 6 6 7 7 8 8 9 9 10
这个我不明白,请解释为什么会这样? 类似地,减法也不像我预期的那样表现
def fun(s: Stream[Int]): Stream[Int] = Stream.cons(s.head - 2, fun(s.tail))
输出
5 6 7 8 9 10 ... up to 18
【问题讨论】:
-
对我来说似乎很正常。您为什么不尝试解释一下您的预期与您得到的,以便有人可以尝试帮助您解决断开连接的位置。