Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Forked from k10526/gist:dcfe72dc7b150aaba1bc
Last active December 18, 2017 15:12
Show Gist options
  • Save jooyunghan/840ee284e9c1968063f7f48e87c692d5 to your computer and use it in GitHub Desktop.
Save jooyunghan/840ee284e9c1968063f7f48e87c692d5 to your computer and use it in GitHub Desktop.
lazy
var noop = [];
function stream(arr){
if(arr.length === 0) return noop;
return cons(function (){return arr[0]}, function (){ return stream(arr.slice(1))})
}
function cons(head, tail){
return [head, tail];
}
function nil(stream) {
return stream === noop;
}
function force(obj) {
if (typeof obj === 'function') {
return obj();
}
return obj;
}
function head(stream) {
return (stream[0] = force(stream[0]));
}
function tail(stream) {
return (stream[1] = force(stream[1]));
}
function foldr(stream, fn, z) {
if (nil(stream)) return z;
else {
return fn(head(stream), function () {
return foldr(tail(stream), fn, z);
});
}
}
function foldl(stream, fn, init) {
var result = init;
while (!nil(stream)) {
result = fn(result, head(stream))
stream = tail(stream);
}
return result
}
function take(stream, n){
return foldr(stream, function (a, rest) {
return function (n) {
if (n <= 0) return noop;
return cons(a, force(rest)(n-1));
};
}, function () { return noop; })(n);
}
function drop(stream, n){
while (n-->0) {
stream = tail(stream);
}
return stream;
}
function some(stream, fn){
return foldr(stream, function(a,rest){
return fn(a) || a();
}, false)
}
const num = n => cons(() => n, () => num(n+1));
function sum(stream) {
return foldr(stream, function(a, b) {
return a + force(b);
}, 0);
}
console.log(take(drop(num(0), 1000000), 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment