如何使用闭包增加方案中的值? [英] How can I increment a value in scheme with closure?

查看:28
本文介绍了如何使用闭包增加方案中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用闭包递增方案中的值?我正在听 sicp 课程的第 3A 课.

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)

推荐答案

使用 set! 来存储递增的值.试试这个:

Use set! for storing the incremented value. Try this:

(define (sum VAL)
  (lambda (x)
    (set! VAL (add1 VAL))
    (* x x VAL)))

因为 VALsum 过程被调用时被包围,每次你调用 a 它都会记住"之前的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)

回答评论:当然可以用let,但不是真的有必要,效果和之前一样.不同的是,在之前的代码中我们修改了一个封闭的函数参数,现在我们正在修改一个封闭的 let 定义的变量,但结果是相同的.但是,如果您需要在初始化 VAL 之前对 n 执行一些操作,这将很有用:

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

这篇关于如何使用闭包增加方案中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆