Scala Streams 及其堆栈内存使用情况
假设,我有一个递归定义的Stream
:例如,
def from(n:Int):Stream[Int] = Stream.cons(n, from(n+1))
我猜它需要恒定的堆栈内存。正确吗?对于任何递归定义的流
来说它是否正确?您能想到任何使用非常量堆栈内存的递归定义的stream
示例吗?
Suppose, I have a recursively-defined Stream
: e.g.
def from(n:Int):Stream[Int] = Stream.cons(n, from(n+1))
I guess it requires constant stack memory. Is it correct? Is it correct for any recursively-defined stream
? Can you think of any recursively-defined stream
example, which uses non-constant stack memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在问访问流是否需要恒定的堆栈内存?
如果是这样,答案是肯定的:
Stream
的apply
是根据drop
定义的(定义在LinearSeqOptimized
),而drop
是尾递归的,因此被编译成while
循环。这使得
drop
本质上如下所示:因此堆栈大小的唯一增加可能来自对
_this.tail
的调用。在from
的定义中,该调用永远不会增加堆栈:它所做的只是构建Stream.cons
的实例(因为递归调用实际上并未在该处进行评估)观点)。Are you asking whether accessing the stream requires constant stack memory?
If so the answer is yes:
apply
forStream
s is defined in terms ofdrop
(the definition is inLinearSeqOptimized
), anddrop
is tail-recursive, so is compiled into awhile
loop.That makes
drop
essentially look as follows:So the only increase in stack size can come from the call to
_this.tail
. In your definition offrom
, that call will never increase the stack: all it does is build an instance ofStream.cons
(since the recursive call is not actually evaluated at that point).