Avoiding symbol capture when using macros to generate functions (or other macros)
Posted
by Rob Lachlan
on Stack Overflow
See other posts from Stack Overflow
or by Rob Lachlan
Published on 2010-05-28T05:10:27Z
Indexed on
2010/05/28
7:51 UTC
Read the original article
Hit count: 511
I'm a bit confused as to exactly when symbol capture will occur with clojure macros. Suppose that I have a macro which defines a function from keywords. In this trivial example,
(defmacro foo [keywd1 keywd2] `(defn ~(symbol (name keywd1))
[~(symbol (name keywd2))] (* 2 ~(symbol (name keywd2)))))
I call (foo :bar :baz), and this gets expanded into (defn bar [baz] (* 2 baz)).
So now the question -- can this lead to symbol capture? If so, under what circumstances? I know that it's preferred to use gensym (e.g. bar#) to prevent symbol capture, but in some cases (not many, but still) I'd like to have a pretty macro-expansion, without the auto-generated symbols.
Bonus question: does the answer change if we are considering a macro that creates macros?
© Stack Overflow or respective owner