I’ve never understood, therefore, the motivation behind trying to “translate” SICP into a language like JS (or Python, etc.) It over emphasizes the importance of the preferred language in a way that very obviously undermines the book.
The point being: if you’re gonna do SICP do it in Scheme. You’ll get more out of it.
One of the two professors (Dr. Sussman) that give the lectures in this series is a co-creator of Scheme.
You don't have to imagine, you can look at the code used in the JS version and it goes through some fun contortions to get around the fact that JS is not expression oriented (like Scheme). This is from page 35 (PDF: https://sicp.sourceacademy.org/sicpjs.pdf):
function count_change(amount) {
return cc(amount, 5);
}
function cc(amount, kinds_of_coins) {
return amount === 0
? 1
: amount < 0 || kinds_of_coins === 0
? 0
: cc(amount, kinds_of_coins - 1)
+
cc(amount - first_denomination(kinds_of_coins),
kinds_of_coins);
}
function first_denomination(kinds_of_coins) {
return kinds_of_coins === 1 ? 1
: kinds_of_coins === 2 ? 5
: kinds_of_coins === 3 ? 10
: kinds_of_coins === 4 ? 25
: kinds_of_coins === 5 ? 50
: 0;
}That certainly works, but it's awkward. Here's the Scheme code from the 2nd edition of SICP:
(define (count-change amount) (cc amount 5))
(define (cc amount kinds-of-coins)
(cond ((= amount 0) 1)
((or (< amount 0) (= kinds-of-coins 0)) 0)
(else (+ (cc amount
(- kinds-of-coins 1))
(cc (- amount
(first-denomination
kinds-of-coins))
kinds-of-coins)))))
(define (first-denomination kinds-of-coins)
(cond ((= kinds-of-coins 1) 1)
((= kinds-of-coins 2) 5)
((= kinds-of-coins 3) 10)
((= kinds-of-coins 4) 25)
((= kinds-of-coins 5) 50)))
The JS code has to use the ternary ?: to get around the fact that it does not have a good equivalent to `cond`. You can see that they've gone through a literal translation of Scheme to JS that results in very unidiomatic JS code.