Reputation: 3542
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!
Upvotes: 1
Views: 125
Reputation: 91349
There are two parts in the length
function:
length-iter
;length-iter
.In the invocation, i.e., line 6, you pass the original items
list 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:
(length-iter items 0)
Thus, items
will be bound to a
, and 0
to count
. You can think of the inner function as a separate function:
(define (length-iter a count)
(if (null? a)
count
(length-iter (cdr a)(+ 1 count))))
And then, think of your length
function as if it just delegated all the work to the length-iter
function:
(define (length items)
(length-iter items 0))
That's what's being done in your function. The difference, is that the length-iter
function is only known to length
.
Upvotes: 4