我试图制作一个用于绑定的宏 变量如果是unbind,否则如果绑定比 追加其价值
(defmacro set-or-nconc (var &rest args)
`(,(if (and (boundp var) (not (null ,var)))
'nconc 'setq)
,var ,@args))
想要的输出是
(set-or-nconc i '(a b)) => '(a b)
i => '(a b)
(set-or-nconc i '(a b)) => '(a b a b)
i => '(a b a b)
但我定义的宏不起作用 如果我被绑定为零 有人知道这个宏有什么问题吗?
答案 0 :(得分:3)
使用setq
或nconc
的决定是在宏扩展时完成的,而不是在运行时完成的。这有点问题。你的反引用表达式也存在一些问题,因为有一个“,”太多(在(null ,var)
中)或太少(在(boundp var)
中,需要另一个反引号)。
以下至少是接近工作解决方案的事情,推迟了在运行时使用setq
或nconc
的选择:
(defmacro set-or-nconc (var &rest args)
`(if (and (boundp ',var) (not (null ,var)))
(nconc ,var ,@args)
(setq ,var ,@args)))
另外请注意,使用它来逐渐构建列表将具有或多或少的O(n ^ 2)行为,通常通过consing积累更快,然后(如果需要)在结束时执行反向。