This is from the SICP course for the environmental model section:
(define make-counter
(lambda (n)
(lambda () (set! n (+ n 1))
n)))
Below,the interpreter says that (make-counter 0)
is a procedure:
> (make-counter 0)
#<procedure:...make_counter.rkt:8:5>
Below, I define c1
to be (make-counter 0)
.
(define c1 (make-counter 0)
Below is where I get confused as to the reason (c1)
returns the counter values instead of "procedure"
.
>(c1)
1
> (c1)
2
> (c1)
3
My thinking process is that if (c1)
points to a procedure, (make-counter)
, then (c1)
should return "procedure:...make_counter.rkt:8:5"
.
Because procedure -> procedure.
I see what should happen, I am just confused, conceptually, as to how and why.
What is your question? Do you doubt it works like the name suggests, or do you not understand how it does?
The first can be tested in 30 seconds, I'll answer the second:
make-counter is a procedure that takes one argument. Now look at the code again: what does it return? A procedure with 0 arguments.
So executing (c1)
will return the numbers from 1 on upwards (if starting with 0).
For completeness:
Gambit v4.8.1
> (define make-counter
(lambda (n)
(lambda () (set! n (+ n 1))
n)))
> (define c1 (make-counter 0))
> (c1)
1
> (c1)
2
> (c1)
3
>
Addition after question edit:
c1
is the procedure, but (c1)
is procedure application, what you would call "calling the procedure" in another programming world.
> c1
#<procedure #2 c1>
> (c1)
1
BTW a nice piece of functional code, if you have understood this you will look at programming differently.
More questions via comment:
Now, its (make-counter 0). Working it by hand, I am not understanding why n is not returned.
The answer is the same we gave you about c1
and (c1)
:
make-counter
returns lambda ()
, and n is only returned if you call the lambda. Functions (in scheme: procedures, lambdas) are values that can be handed around, functional programming principle. You have to call them (correct term: apply) the get the procedure result.
Now tell me: how do you call a procedure in scheme?
more edits:
Okay, we call a procedure in scheme by enclosing it in parens.
Now tell me: What is the substitution step for (c1)
?