在Common Lisp中,我可以在SBCL中评估以下代码片段,而不会收到任何语法错误的信号:
有人知道为什么这在Scheme中无法实现吗?
(let ((x 0))
(defun my-incf (y)
(setf x (+ x y)))
(defun my-decf (y)
(setf x (- x y))))
MY-DECF
CL-USER> (my-incf 1)
1
CL-USER> (my-incf 1)
2
CL-USER> (my-decf 1)
1
CL-USER> (my-decf 1)
0
当我尝试评估一个相应的Scheme代码片段(在DrRacket中)时:
(let ((x 0))
(define (my-incf y)
(set! x (+ x y)))
(define (my-decf y)
(set! x (- x y))))
这表示出现了语法错误。
begin (possibly implicit): no expression after a sequence of internal definitions in: (begin (define (my-incf y) (set! x (+ x y))) (define (my-decf y) (set! x (- x y))))
有人知道为什么这在Scheme中无法实现吗?
(defvar *counter* 0)
来解决,并让函数引用*counter*
。如果该模块需要支持多个实例并且所有这些全局变量应该是其实例变量,则可以采用面向对象的方法。如果您不预计需要多个实例或任何继承等好处,请使用全局变量。动态变量是处理全局变量的“Common Lispy”方式。 - Kaz