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:
(define (sum VAL)
(lambda (x)
(set! VAL (add1 VAL))
(* x x VAL)))
Because VAL
was enclosed at the time the sum
procedure was called, each time you call a
it'll "remember" the previous value in VAL
and it'll get incremented by one unit. For example:
(define a (sum 5)) ; VAL = 5
(a 3) ; VAL = 6
=> 54 ; (* 3 3 6)
(a 3) ; VAL = 7
=> 63 ; (* 3 3 7)
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 enclosed let
-defined variable, but the result is identical. However, this would be useful if you needed to perform some operation on n
before initializing VAL
:
(define (sum n)
(let ((VAL n))
(lambda (x)
(set! VAL (add1 VAL))
(* x x VAL))))