Streams.js: a lazy evaluation in JavaScript library
JavaScript library (stream.js) introduces a "new" numerical data structure: streams. This container is similar to an array and a linked list, but it contains an unlimited number of elements that are realized by a lazy evaluation.
var s = Stream.range (10, 20);
s.print (); // prints the numbers from 10 to 20
You can specify only the beginning of the range Stream.range (low) for an argument Stream.range (low, high), then the stream will consist of an unlimited natural numbers. Stream.range () starts with 1 by a default.
The idea of supposedly "infinite" range simplifies the programming. For example, in this way, a list of odd and even numbers is produced.
var naturalNumbers = Stream.range(); // naturalNumbers is now 1, 2, 3, ...
var evenNumbers = naturalNumbers.map( function (x) {
return 2 * x;
}); // EvenNumbers is now 2, 4, 6, ...
var oddNumbers = naturalNumbers.filter( function (x) {
return x % 2 != 0;
}); // OddNumbers is now 1, 3, 5, ...
evenNumbers.take (3). print(); // prints 2, 4, 6
oddNumbers.take (3). print(); // prints 1, 3, 5
Creating of your own streams with the given parameters is possible with a new Stream( head, functionReturningTail ). For example, here is a concise way to list the natural numbers.
function ones() {
return new Stream( 1, ones );
}
function naturalNumbers() {
return new Stream(
// The natural numbers are the stream whose first element is 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
P.S. Here is a similar concept of a lazy evaluation, but with a different syntax that is implemented in linq.js and node-lazy, so that the author is not quite correct to call lists of "new data structure" for JavaScript.
Library streams.js on CoffeScript: coffeestream.
![]() |
![]() |
|
Vote for this post
Bring it to the Main Page |
||
![]() |
![]() |
Comments
Leave a Reply