2015-10-20 23 views
0

访问变量可以说我有方案如下闭合,增加计数器每次它被称为:计划 - 在封闭

(define count 
    (let ((next 0)) 
    (lambda() 
     (set! next (+ next 1)) 
     next))) 

我的问题很简单,我怎么能重新写这个函数这样我就可以在不增加计数器的情况下访问next的值?我尝试过使用lambda表达式,但我似乎无法弄清楚。

编辑:一些背景:

(define (dispatch m) 
    (let ((count 0)) 
     (cond ((eq? m 'withdraw) withdraw) ; Increments count 
       ((eq? m 'deposit) deposit) ; Increments count 
       ((eq? m 'balance) balance-return) 
       ((eq? m 'transaction) count) ; "count" on this line should return the value 
       (else (error "Unknown request -- MAKE-ACCOUNT" 
          m))))) 
+0

你可以举一个使用'next'值的代码示例吗? –

+0

添加到主要问题。 – nbduckman

+2

在你提供的例子中,总是返回内层的count(在这种情况下为0),因为你用let绑定它。您必须在'dispatch'函数内改变'count'的定义。我想这就是你要做的,但我不确定 –

回答

3

这不是完全清楚的count如何与银行账户例子,但一些如

(define (make-account) 
    (let ((count 0)) ; Define `count` here... 
     (define (dispatch m) ; ...and define `dispatch` such that `count` is in scope 
      (cond ((eq? m 'next) ; On message 'next... 
        (lambda() (set! count (+ count 1)))) ; ...return the lambda, which has `count` in its scope 
        ((eq? m 'count) ; On message 'count... 
        count) ; ...return the current count 
        (else ; Otherwise... 
        (error "Unknown request -- MAKE-ACCOUNT" m)))) ...raise error 
     dispatch)) ; Return `dispatch` from `make-account` 

简单可能是你在找什么对于。

主要思想是:

  1. 建立在您的变量可以住一个范围(这里的make-account程序的范围)
  2. 在该范围内(这里:(let ((count 0)))创建您的变量
  3. 只是在范围内访问它(这里:设置或获取count
  4. 返回东西有范围内的变量(这里:dispatch封闭)。

然后可以(define acc-dispatch (make-account)),并随后检索使用(acc-dispatch 'count)当前计,但你仍然可以增加它,如果你想使用((acc-dispatch 'next))

请注意,后者适用通过调用(acc-dispatch 'next)返回的lambda。

+0

谢谢,问题在于我的'(let((count 0))'是在哪里,它是在不正确的范围。把它放在main函数定义实现了我想要的结果。谢谢:) – nbduckman