我想知道是否可以从类似(伪代码)的循环动态构建COND子句:
(defvar current-state 1)
(defmacro mymacro() (条件 `(循环(状态。回调)处于可能状态 …
宏在编译时扩展,所以你的 possible-states 变量必须是编译时常量。如果不是这种情况(或者如果您不清楚上述我的意思),您应该这样做 的 不 强> 在这里使用宏。
possible-states
改为使用函数:
(funcall (cdr (find current-state possible-states :key #'car :test #'eq)))
要么
(funcall (cdr (assoc current-state possible-states :test #'eq)))
或者,更好的是,让你的 possible-states 一个 哈希 表 而不是一个 协会 名单 :
(funcall (gethash current-state possible-states))
但是,如果你的 possible-states 的 是 强> 一个编译时间常数,你 实际上可以使用宏,除了你可能想要使用 case 代替 cond :
case
cond
(defmacro state-dispatch (state) `(case ,state ,@(mapcar (lambda (cell) `((,(car cell)) (,(cdr cell)))) possible-states))) (defparameter possible-states '((1 . foo) (2 . bar))) (macroexpand-1 '(state-dispatch mystate)) ==> (CASE MYSTATE ((1) (FOO)) ((2) (BAR))) ; T
请注意 速度 的观点, gethash 版本可能与宏版本相同(至少它不慢)。
gethash