How can I increment a value in scheme with closure?

被刻印的时光 ゝ 提交于 2019-12-02 22:57:09

问题


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)

回答1:


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))))


来源:https://stackoverflow.com/questions/24214632/how-can-i-increment-a-value-in-scheme-with-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!