Skip to content

Instantly share code, notes, and snippets.

@k10526
Last active December 18, 2017 15:14
Show Gist options
  • Save k10526/dcfe72dc7b150aaba1bc to your computer and use it in GitHub Desktop.
Save k10526/dcfe72dc7b150aaba1bc to your computer and use it in GitHub Desktop.
lazy
var noop = [];
function clone (arr){
return arr.slice(0);
}
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 reduce(stream, fn, init){
if(stream===noop) return init;
else {
return fn(function() {
return reduce(stream[1](), fn, init)
}, stream[0]())
}
}
function map(stream, fn){
return reduce(stream, function (a, v){
return cons(function (){return fn(v)}, a);
}, noop)
}
function filter(stream, fn){
return reduce(stream, function (a, v){
if(fn(v))return cons(function (){return v}, a);
return a();
}, noop)
}
function toArray(stream){
var arr = [];
reduce(stream, function(acc, v){
arr.push(v)
return acc();
}, noop);
return arr;
}
function take(stream, n){
return reduce(stream, function(a, v){
if(n <= 0) return noop;
return cons(function(){return v}, function(){return take(a(),n-1)});
}, noop)
}
function drop(stream, n){
if(stream === noop) return noop;
if(n>0) return drop(stream[1](),n-1);
return stream;
}
function some(stream, fn){
return reduce(stream, function(a,v){
return fn(v) || a();
}, false)
}
function all(stream, fn){
return reduce(stream, function(a,v){
return fn(v) && a();
}, true)
}
c = filter(
map(stream([1,2,3,4,5,6,7,8,9,10]),
function(v){console.log('map:'+v);return v+1;}),
function(v){console.log('filter:'+v);return v%2})
console.info(c[0]());
console.info(c[1]()[0]());
console.info(toArray(take(c,2)));
console.info(toArray(drop(c,2)));
console.info(all(c, function(v){return v<12}));
console.info(all(c, function(v){return v<6}));
console.info(some(c, function(v){return v>10}));
console.info(some(c, function(v){return v<0}));
@jennifer-walters
Copy link

어려워오. 주석주새오.

@jooyunghan
Copy link

reduce 구현이 적절하지 않아보이네요. stream 은 기본 구현을 foldr (foldRight) 형태로 가져가야 합니다.
console.log(take(drop(num(0), 1000000), 1)) 같은 걸 해보면 reduce 구현때문에 스택오버플로가 납니다.
https://gist.github.com/jooyunghan/840ee284e9c1968063f7f48e87c692d5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment