宏:如何在带反引号的生成代码中输出逗号?

时间:2019-05-03 14:56:10

标签: common-lisp

我有一个格式如下的宏:

;; Macro wich does a sort of defun for instance, with some other stuff.
(defmacro def2 (name (&rest args) &body body)
  `(defun ,(intern (string-upcase name)) (,@args)
     ,@body))

我想生成很多def2

(defmacro defdefs ()
  `(progn
     ,@(loop for name in '("name1" "name2" "name3")
         collect `(def2 ,name (&rest args)
            (print ,@args))))) ; <---- HERE.

我想以args的形式引用def2,但是如果我写,@args,它将引用defdefs宏中的变量(未定义)。 我曾考虑使用macro-functionapply之类的东西,但是有更好的方法告诉defdefs我要输出此列表: (print ,@args)并没有在宏扩展过程中评估,@args部分?

我尝试使用引号,双引号,反引号和双反引号,但是我找不到解决方案...

谢谢。

1 个答案:

答案 0 :(得分:4)

CL-USER 33 > (defmacro def2 (name (&rest args) &body body)
               `(defun ,(intern (string-upcase name)) (,@args)
                  ,@body))
DEF2

CL-USER 34 > (defmacro defdefs ()
               `(progn
                  ,@(loop for name in '("name1" "name2" "name3")
                          collect `(def2 ,name (&rest args)
                                     (print args)))))
DEFDEFS

CL-USER 35 > (pprint (macroexpand '(defdefs)))

(PROGN
  (DEF2 "name1" (&REST ARGS) (PRINT ARGS))
  (DEF2 "name2" (&REST ARGS) (PRINT ARGS))
  (DEF2 "name3" (&REST ARGS) (PRINT ARGS)))

CL-USER 36 > (pprint (macroexpand-1 '(DEF2 "name1" (&REST ARGS) (PRINT ARGS))))

(DEFUN NAME1 (&REST ARGS)
  (PRINT ARGS))