マクロの変数捕捉

説明用のシンプルな例を思いついたのでメモ。

例えばmy-orを次のように定義したとする。

(define-macro (my-or test1 test2)
  `(let ((x ,test1)) (if x x ,test2)))

しかしこれでは、以下の場合に正しい結果を返さない。

gosh> x
#t
gosh> (or #f x)
#t
gosh> (my-or #f x)
#f

なぜならば、このように展開されているから。

gosh> (macroexpand '(my-or #f x))
(let ((x #f)) (if x x x))