function accumulate(combiner, null_value, term, a, next, b){
return a > b
? null_value
: combiner(term(a),
accumulate(combiner, null_value, term, next(a), next, b));
}
function accumulate_(combiner, null_value, term, a, next, b){
function iter(a, result) {
return a > b
? result
: iter(next(a), combiner(term(a), result));
}
return iter(a, null_value);
}
function sum_a(term, a, next, b){
function plus(x, y){
return x + y;
}
return accumulate(plus, 0, term, a, next, b);
}
function sum_b(term, a, next, b){
function plus(x, y){
return x + y;
}
return accumulate_(plus, 0, term, a, next, b);
}
function identity(x) {
return x;
}
function filtered_accumulate(combiner, null_value, term, a, next, b, filter) {
return a > b
? null_value
: filter(a)
? combiner(term(a), filtered_accumulate(combiner, null_value, term, next(a), next, b, filter))
: filtered_accumulate(combiner, null_value, term, next(a), next, b, filter);
}
function prime_sum(a, b){
function plus(x,y){
return x+y;
}
return filtered_accumulate(plus, 0, square, a, next, b, is_prime);
}
prime_sum(4,10);
function relative_prime(n){
function plus(x,y){
return x+y;
}
function test(x){
return gcd(x, n) === 1;
}
return filtered_accumulate(plus, 1, identity, 1, next, n, test);
}
relative_prime(8);
js의 reduce를 직접 구현해보는 과정
728x90