I'm reading SICP and using Dr Racket SICP package as IDE and interpreter. Code from SICP:
(define (sum func a next b)
(if (> a b)
0
(+ (func a)
(sum func (next a) next b))))
(define (inc n) (+ n 1))
(define (sum-cubes a b)
(sum cube a inc b))
(define (cube a) (* a a a))
(sum-cubes 1 10)
The function is to calculate the sum of cubic from 1 to 10. However I have no idea what does next b
mean, as we are increasing a
instead of b, and the increment function is represented by inc
.
So I removed the next
in next b
Then I got the error:
define: duplicate argument identifier in: next
I tried to look up "next" in syntax but found nothing.
Somehow I made this work:
(define (sum func a b)
(if (> a b)
0
(+ (func a)
(sum func (inc a) b))))
(define (inc n) (+ n 1))
(define (sum-cubes a b)
(sum cube a b))
(define (cube a) (* a a a))
(sum-cubes 1 10)
But this seems strange. func
is replaced by cube
, so it's pretty much like a function parameter in C++? But how come it is not (func (inc a))
? How come Scheme recognize func (inc a)
and knows that it needs to replace it with cube
?
next
is just a parameter that happens to be a function. It's passed the value inc
, so the fragment (next a)
in function sum
is computing (inc a)
. The following next b
is just passing these values on to the recursive invocation of sum
.
Addition
The recursive call just increments the value passed to a
and lets b
as-is. The recursion stops when a > b
. At each level func
is applied to a
and added to the value being accumulated. func
is the function cube
in the example. So it's summing cubes as intended.