CS/SICP in JS

연습문제 1.32, 1.33

띵킹 2023. 2. 19. 13:26
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

'CS > SICP in JS' 카테고리의 다른 글

연습문제 1.35  (0) 2023.02.19
연습문제 1.34  (0) 2023.02.19
연습문제 1.31  (0) 2023.02.18
연습문제 1.30  (0) 2023.02.18
연습문제 1.17  (0) 2023.02.11