有人可以向我解释“卫生"的概念吗(我是一名计划程序员)? [英] Can someone explain the concept of 'hygiene' to me (I'm a scheme programmer)?

查看:58
本文介绍了有人可以向我解释“卫生"的概念吗(我是一名计划程序员)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以...我是r6rs计划的新手,正在学习宏.有人可以向我解释卫生"是什么意思吗?

So... I'm new to scheme r6rs, and am learning macros. Can somebody explain to me what is meant by 'hygiene'?

谢谢.

推荐答案

卫生通常在宏的上下文中使用.卫生宏不使用可能会干扰正在扩展的代码的变量名.这是一个例子.假设我们想用宏定义 or 特殊形式.凭直觉,

Hygiene is often used in the context of macros. A hygienic macro doesn't use variable names that can risk interfering with the code under expansion. Here is an example. Let's say we want to define the or special form with a macro. Intuitively,

(或abc ... d)将扩展为(let((tmp a))(如果tmp a(或bc ... d)))之类的东西.(为简单起见,我省略了空的(或)情况.)

(or a b c ... d) would expand to something like (let ((tmp a)) (if tmp a (or b c ... d))). (I am omitting the empty (or) case for simplicity.)

现在,如果实际上在代码中添加了 tmp 这样的草图扩展名,那将是不卫生的,并且很糟糕,因为它可能会干扰具有相同名称的另一个变量.说,我们想评估

Now, if the name tmp was actually added in the code like in the above sketched expansion, it would be not hygienic, and bad because it might interfere with another variable with the same name. Say, we wanted to evaluate

(let ((tmp 1)) (or #f tmp))

使用我们的直观扩展,它将变成

Using our intuitive expansion, this would become

(let ((tmp 1)) (let ((tmp #f)) (if tmp (or tmp)))

宏中的 tmp 遮盖了最外面的 tmp ,因此结果是 #f 而不是 1 .

The tmp from the macro shadows the outer-most tmp, and so the result is #f instead of 1.

现在,如果宏是卫生的(在Scheme中,使用 syntax-rules 时会自动出现这种情况),而不是使用名称 tmp 进行扩展,则应使用保证不会在代码中其他任何地方出现的符号.您可以在Common Lisp中使用 gensym .

Now, if the macro was hygienic (and in Scheme, it's automatically the case when using syntax-rules), then instead of using the name tmp for the expansion, you would use a symbol that is guaranteed not to appear anywhere else in the code. You can use gensym in Common Lisp.

Paul Graham的On Lisp 具有有关宏的高级资料.

Paul Graham's On Lisp has advanced material on macros.

这篇关于有人可以向我解释“卫生"的概念吗(我是一名计划程序员)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆