Macro in LISP (LISP中宏的要义)

文章片段来自:

Practical Common LispSyntax and Semantics


The evaluation of a macro form proceeds in two phases: First, the elements of the macro form are passed, unevaluated, to the macro function. Second, the form returned by the macro function--called its-expansion--is evaluated according to the normal evaluation rules.
It's important to keep the two phases of evaluating a macro form clear in your mind. It's easy to lose track when you're typing expressions at the REPL because the two phases happen one after another and the value of the second phase is immediately returned. But when Lisp code is compiled, the two phases happen at completely different times, so it's important to keep clear what's happening when. For instance, when you compile a whole file of source code with the functionCOMPILE-FILE, all the macro forms in the file are recursively expanded until the code consists of nothing but function call forms and special forms. This macroless code is then compiled into a FASL file that theLOADfunction knows how to load. The compiled code, however, isn't executed until the file is loaded. Because macros generate their expansion at compile time, they can do relatively large amounts of work generating their expansion without having to pay for it when the file is loaded or the functions defined in the file are called.
For now the important thing for you to realize is that macros--while syntactically similar to function calls--serve quite a different purpose, providing a hook into the compiler.


计算一个宏表格分为两步处理:第一步,宏表格中的元素被原样不动的传递给宏函数(即宏)。第二步,宏函数返回表格--S表达式,被以正常的方式计算其结果。


你应该牢记计算一个宏要分两步。这很容易搞混,你在REPL打表达式时,因为两个阶段是连接在一起的,第二阶段的值就直接返回了。但是当Lisp代码被编译时,两个阶段就在完全不同的两个时间,所以有必要搞清楚什么时候会发生什么。举个例子,当你用COMPILE-FILE编译一段源码时,文件中所有的宏都会被递归展开,直到只剩下函数和特殊函数。这些无宏代码被编译成FASL文件(fast-load file),被LOAD 函数加载。然而,编译后的代码在加载前是不会执行的。所以,宏在编译时展开,他们能在编译时做大量的扩展工作,而不用在加载或者函数调用时花时间。(译者:这是宏之所以称之为宏的原因。)


现在你要关注的是:宏虽然在语法上很像函数调用,但却有着截然不同的目的:为编译时提供一个连接器。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值