How can I increment a value in scheme with closure?

前端 未结 1 1724
逝去的感伤
逝去的感伤 2021-01-28 01:03

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?
         


        
相关标签:
1条回答
  • 2021-01-28 01:23

    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))))
    
    0 讨论(0)
提交回复
热议问题