浏览
Hacker News和我碰到了
http://streamjs.org/,这是一个在JavaScript中的惰性评估集合的实现.
其中一个例子是:
- function ones() {
- return new Stream( 1,ones );
- }
- function naturalNumbers() {
- return new Stream(
- // the natural numbers are the stream whose first element is 1...
- 1,function () {
- // and the rest are the natural numbers all incremented by one
- // which is obtained by adding the stream of natural numbers...
- // 1,2,3,4,5,...
- // to the infinite stream of ones...
- // 1,1,...
- // yielding...
- // 2,6,...
- // which indeed are the REST of the natural numbers after one
- return ones().add( naturalNumbers() );
- }
- );
- }
- naturalNumbers().take( 5 ).print(); // prints 1,5
也许晚上太晚了,我错过了这一点,但我不明白如何打印1,5.我会期望它打印1,2和死亡的无限深递归.我明白如何打印无限的1.我没有得到自然人如何工作.
通过我的(显然是不正确的)逻辑,第一次调用naturalNumbers返回的Stream的头将为1,流中的下一个元素被评估为1().add(naturalNumbers());这是一个().add(1),后跟一个().add(naturalNumbers()),将重新设置为1等等…
真的很感激,如果有人会在这方面有所作为.
解决方法
- naturalNumbers[0] = 1 // by definition
- naturalNumbers[1] = ones[0] + naturalNumbers[0] = 1 + 1 = 2
- naturalNumbers[2] = ones[1] + naturalNumbers[1] = 1 + 2 = 3
- naturalNumbers[3] = ones[2] + naturalNumbers[2] = 1 + 3 = 4
- ...
关键的是,function(){return ones().add(naturalNumbers())}不返回一个元素,它返回一个流.在这种情况下,由该流生成后续元素,即“求和”流.因此,与ones()不同,naturalNumbers()不直接调用它.相反,它间接地调用自身,由总结流介导.