Fin*_*arr 10 javascript functional-programming lazy-evaluation
浏览黑客新闻,我遇到了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, 1, 1, 1, ...
// yielding...
// 2, 3, 4, 5, 6, ...
// which indeed are the REST of the natural numbers after one
return ones().add( naturalNumbers() );
}
);
}
naturalNumbers().take( 5 ).print(); // prints 1, 2, 3, 4, 5
Run Code Online (Sandbox Code Playgroud)
也许现在已经太晚了,我错过了这一点,但我不明白这是怎么打印1,2,3,4,5.我希望它能打印1,2,2,2,2并且无限深度递归.我理解ones将如何打印无限1.我不知道如何naturalNumbers工作.
通过我的(显然不正确的)逻辑,所述head的Stream由所述第一呼叫返回到naturalNumbers将是1,并且在流中的下一个元素作为评价ones().add( naturalNumbers() );其ones().add(1)随后ones().add( naturalNumbers() )将reeavulate至1等等...
如果有人能对此有所了解,我将非常感激.
WRe*_*ach 11
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
...
Run Code Online (Sandbox Code Playgroud)
关键点是function() { return ones().add(naturalNumbers()) }不返回元素,它返回一个流.后续元素由该流生成,在这种情况下是"求和"流.因此,与之不同ones(),naturalNumbers()不会直接调用自己.相反,它间接地调用自己 - 由求和流调解.
| 归档时间: |
|
| 查看次数: |
7800 次 |
| 最近记录: |