sicp icon indicating copy to clipboard operation
sicp copied to clipboard

Exercise 3.16 - Solution

Open devinryu opened this issue 2 years ago • 1 comments

// SICP JS 3.3.1

function count_pairs(x) {
    return ! is_pair(x)
           ? 0
           : count_pairs(head(x)) + 
             count_pairs(tail(x)) +
             1;
}

const three_list = list("a", "b", "c");

const one = pair("a", "b");
const three = pair(one, one);
const four = pair(three, "c");
const seven = pair(three, three);

// return 3; return 4; return 7;

display(count_pairs(three_list));
display(count_pairs(four));
display(count_pairs(seven));

// never return at all

function last_pair(x) {
    return is_null(tail(x))
           ? x
           : last_pair(tail(x));
}

function make_cycle(x) {
    set_tail(last_pair(x), x);
    return x;
}

const cycle = make_cycle(three_list);

display(count_pairs(cycle));

devinryu avatar Aug 28 '22 02:08 devinryu

Thanks for this. If you have time, feel free to make a PR. If not, I'll make one when I find the time.

martin-henz avatar Aug 28 '22 09:08 martin-henz