common-lisp - 宏: How to output a comma in a backquoted generated code?

标签 common-lisp

我有一个以下形式的宏:

;; Macro which 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.

我想引用 def2 形式中的 args,但是如果我写 ,@args 它将引用一个变量(未定义)在 defdefs 宏中。 我曾想过使用宏函数和应用之类的东西,但是有没有更好的方法来告诉 defdefs 我想输出这个列表: (print ,@args) 在宏展开期间不评估 ,@args 部分?

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

提前谢谢您。

最佳答案

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))

关于common-lisp - 宏: How to output a comma in a backquoted generated code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972371/

相关文章:

comparison - 为什么集差函数不能将列表与文件中的数据进行比较?

lisp - 存储 ql :system-apropos into a variable 返回的包名

common-lisp - SBCL: asdf:load-system 在定义字符串常量时失败

clojure - 无参数(和)返回 t

format - 是否有格式指令可以迭代 Common Lisp 中的向量?

common-lisp - 如何在 Common Lisp 中编写类似的函数?

function - Common Lisp - 使用一个函数作为另一个函数的输入

algorithm - 砍掉棍子 HackerRank 挑战 Lisp 实现

lisp - 使用 Lisp : define a function that takes a list and a number and returns true if the number occurs in the list

macros - OnLisp 中的 CONDLET 宏对我来说并不简单