How can I increment a value in scheme with closure? I'm on lecture 3A in the sicp course.
(define (sum VAL)
// how do I increment VAL everytime i call it?
(lambda(x)
(* x x VAL)))
(define a (sum 5))
(a 3)
How can I increment a value in scheme with closure? I'm on lecture 3A in the sicp course.
(define (sum VAL)
// how do I increment VAL everytime i call it?
(lambda(x)
(* x x VAL)))
(define a (sum 5))
(a 3)
Use
set!
for storing the incremented value. Try this:Because
VAL
was enclosed at the time thesum
procedure was called, each time you calla
it'll "remember" the previous value inVAL
and it'll get incremented by one unit. For example:Answering the comment: sure, you can use
let
, but it's not really necessary, it has the same effect as before. The difference is that in the previous code we modified an enclosed function parameter and now we're modifying an enclosedlet
-defined variable, but the result is identical. However, this would be useful if you needed to perform some operation onn
before initializingVAL
: