顶级环境中的过程与宏
我将感谢您帮助理解在下文描述的情况下过程和宏之间的行为差异。
情况 1(程序)
(define bar (lambda (x) (foo x))) ; closure of 'bar' contains top-level...
; ... environment where 'foo' is not bound yet
;
(define foo (lambda (x) (* x 4))) ; now, 'foo' is bound in top-level environment
;
(bar 2) ; ==> 8 ; when this line is evaluated, 'foo' is available in ...
; ... the top-level environment, so in the closure of 'bar'
这对我来说似乎是合理的。
情况 2(宏)
让我们尝试在第二行中使用宏而不是过程:
(define bar (lambda (x) (foo x))) ; closure of 'bar' contains...
; ... top-level environment where 'foo' is not bound yet
;
(define-syntax foo
(syntax-rules ()
((foo arg1) (* 4 arg1)))) ; I thought that 'foo' was bound in...
; ... top-level environment to the macro
;
(bar 2) ; ==> ERROR: reference to undefined identifier: foo
我不明白该错误。为什么在评估 (bar 2) 时绑定“foo <--> Macro”不可见,而它位于顶级环境中,所以在“bar”的闭包中?
交换第一个第二行解决了问题,但我不明白为什么:
(define-syntax foo
(syntax-rules ()
((foo arg1) (* 4 arg1))))
;
(define bar (lambda (x) (foo x)))
;
(bar 2) ; ==> 8
提前感谢您的帮助! :-)
此致,
尼古拉斯
I would appreciate your help to understand the difference in behaviour between procedure and macro in the cases described here-after.
Situation 1 (procedure)
(define bar (lambda (x) (foo x))) ; closure of 'bar' contains top-level...
; ... environment where 'foo' is not bound yet
;
(define foo (lambda (x) (* x 4))) ; now, 'foo' is bound in top-level environment
;
(bar 2) ; ==> 8 ; when this line is evaluated, 'foo' is available in ...
; ... the top-level environment, so in the closure of 'bar'
This seems sound to me.
Situation 2 (macro)
Let's try to use a macro instead of a procedure in the 2nd line:
(define bar (lambda (x) (foo x))) ; closure of 'bar' contains...
; ... top-level environment where 'foo' is not bound yet
;
(define-syntax foo
(syntax-rules ()
((foo arg1) (* 4 arg1)))) ; I thought that 'foo' was bound in...
; ... top-level environment to the macro
;
(bar 2) ; ==> ERROR: reference to undefined identifier: foo
I do not understand the error. Why isn't the binding "foo <--> macro" visible when (bar 2) is evaluated whereas it is in the top-level environment, so in the closure of 'bar'?
Swapping the 1st and 2nd line resolves the problem, but I do not understand why:
(define-syntax foo
(syntax-rules ()
((foo arg1) (* 4 arg1))))
;
(define bar (lambda (x) (foo x)))
;
(bar 2) ; ==> 8
Thanks in advance for your help! :-)
Yours sincerely,
Nicolas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在工作版本中,由于宏已经定义,系统将扩展宏,因此您实际上得到:
但是,在非工作版本中,宏尚未定义,并且不会扩展。在运行时,
bar
函数期望找到foo
过程,但该过程并不存在。In the working version, because the macro was already defined, the system will expand the macro, so you effectively get:
However, in the non-working version, the macro wasn't yet defined, and it doesn't get expanded. At run-time, the
bar
function expects to find thefoo
procedure, which doesn't exist.