宏扩展可以包含(声明...)表达式吗? [英] Can macro expansion contain (declare ...) expressions?
问题描述
Common Lisp Hyperspec指出宏形式不能扩展成声明;声明表达式必须作为它们所引用的形式的实际子表达式出现."
The Common Lisp Hyperspec states "Macro forms cannot expand into declarations; declare expressions must appear as actual subexpressions of the form to which they refer."
我对扩展为"的含义感到困惑.诸如此类的宏由于明显的原因而无法正常工作:
I'm confused on the meaning of "expand into". A macro such as the following won't work for obvious reasons:
(defmacro optimize-fully ()
`(declare (optimize (speed 3) (safety 0))))
但是,如果宏扩展仅包含一个(declare ...)
表达式怎么办?
But what if the macro expansion merely contains a (declare ...)
expression?
(defmacro defun-optimized (name (&rest lambda-list) &rest body)
`(defun ,name ,lambda-list
(declare (optimize (speed 3) (safety 0)))
,@body))
(defun-optimized foobar (a b)
(* a b))
这是否违反规范?我使用的CL实施SBCL并没有抱怨,实际上,上面的宏似乎完全按照预期的方式工作.有什么作用?
Is this a violation of the spec? The CL implementation I use, SBCL, does not complain, and in fact, the macro above seems to work precisely as expected. What gives?
推荐答案
第一个示例正是它所禁止的.您不能将像这样的代码与类似这样的东西组合在一起:
Your first example is exactly what it's prohibiting. You couldn't have code like that combined with something like this:
(defun optimized (a b)
(optimize-fully)
(+ a b))
不过,有时我会看到这样的代码:
I sometimes see code like this, though:
(defvar *optimization-settings* '(optimize (speed 3) (safety 0)))
(defun foo (a b)
(declare #.*optimization-settings*)
...)
这篇关于宏扩展可以包含(声明...)表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!