gpt4 book ai didi

lisp - Common Lisp 和 Scheme 词法闭包的区别

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:01 26 4
gpt4 key购买 nike

在 Common Lisp 中,我可以评估以下代码片段(在 SBCL 中)而不会被提示任何语法错误:

(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 中不能这样做的原因吗?

最佳答案

在 Scheme 中,您不能在顶级之外定义顶级绑定(bind)。 (并且 let 的内部肯定是在顶层之外——相反,您拥有的是内部定义,这些定义不会导出到顶层。)但是,使用 define-values,你仍然可以做你需要做的事情:

(define-values (my-incf my-decf)
(let ((x 0))
(values (lambda (y)
(set! x (+ x y))
x)
(lambda (y)
(set! x (- x y))
x))))

但是,您仍然可以使用内部定义,使您的代码更具可读性:

(define-values (my-incf my-decf)
(let ((x 0))
(define (my-incf y)
(set! x (+ x y))
x)
(define (my-decf y)
(set! x (- x y))
x)
(values my-incf my-decf)))

两全其美。 :-) 在这种情况下,values 将内部 my-incfmy-decf 定义发送到外部 define-values ,这是真正的顶级定义发生的地方。

关于lisp - Common Lisp 和 Scheme 词法闭包的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com