tob*_*ats -5 scheme variable-assignment
我不知道发生了什么,但我无法得到这个.
我已经做了很多非常相似的问题,但由于某些原因我无法得到这个问题.
我正试图做一个反击.
(define (make-counter init)
(let ((count init))
((lambda (x)
(begin (set! count (+ count x)) count))1)))
Run Code Online (Sandbox Code Playgroud)
它不会起作用.我如何将状态引入其中?我不知道我以为我知道但它不起作用.我认为创建一个像这样的局部变量会使它工作,但事实并非如此,无论我做什么,价值永远不会改变.我的问题是使初始值可调,我可以让它工作没有它,但不是.
您的代码中存在一些问题.你不必begin在lambda表单的主体内部使用它,它是隐含的.并且不需要lambda将初始值作为参数应用(1在问题的代码中),你想要的是返回lambda包含count变量的那个.试试这个:
(define (make-counter init)
(let ((count init))
(lambda (x)
(set! count (+ count x))
count)))
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
; counter is a procedure, with an internal variable initialized to 10
(define counter (make-counter 10))
; check that the variable was correctly initialized
(counter 0)
=> 10
; add 2 to the internal variable
(counter 2)
=> 12
; add 3 to the internal variable
(counter 3)
=> 15
Run Code Online (Sandbox Code Playgroud)