这是一个简单的宏with-collector
,应该可以解决问题:
(defmacro with-collector ((&optional (collector-name 'collect)) &body body)
(let ((result (gensym)))
`(let ((,result (list)))
(flet ((,collector-name (arg) (push arg ,result)))
(progn ,@body)
(when ,result
(nreverse ,result)))))
它collect
默认使用名称:
(with-collector ()
(collect 'a)
(collect 'b)); => (A B)
但如果您愿意,您可以使用其他名称(例如,用于嵌套或解决符号冲突)
(with-collector (foo)
(foo 'bar)
(foo 'baz)); => (BAR BAZ)
要将它与您的宏集成,只需包装do
表单:
(defmacro do-bits ((var x) &rest body)
"Evaluates [body] forms after binding [var] to each set bit in [x]"
(let ((k (gensym)))
`(with-collector ()
(do ((,k ,x (logand ,k (1- ,k))))
((= ,k 0))
(let ((,var (logand ,k (- ,k))))
,@body)))))
并将collect
在正文中可用:
(do-bits (x 255) (collect x))
; => (1 2 4 8 16 32 64 128)
(do-bits (x 256) (collect x))
; => (256)