sicp
sicp copied to clipboard
Exercise 3.16 - Solution
// 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));
Thanks for this. If you have time, feel free to make a PR. If not, I'll make one when I find the time.