This is an example from the book I am reading:
1 (define (length items)
2 (define (length-iter a count)
3 (if (null? a)
4 count
5 (length-iter (cdr a)(+ 1 count))))
6 (length-iter items 0))
What I am not understanding is how can length-iter know about count? The first time this
procedure is called with a list, it will in turn define another procedure with two argumenets, I get that much. But how does it know that a is the list items? It hasnt reached line 6 yet, where items is passed to length-iter as the argument a. Somehow though it already knows this and is able to make the computation. Any help in clarifying this a bit is appreciated!
There are two parts in the
lengthfunction:length-iter;length-iter.In the invocation, i.e., line 6, you pass the original
itemslist to the inner function as an argument. This is where the inner function gets called. Previously, you are just defining the function, not calling it:Thus,
itemswill be bound toa, and0tocount. You can think of the inner function as a separate function:And then, think of your
lengthfunction as if it just delegated all the work to thelength-iterfunction:That’s what’s being done in your function. The difference, is that the
length-iterfunction is only known tolength.