unqualified symbol 概念,不是很清楚

27 views
Skip to first unread message

Xiaojun Weng

unread,
Feb 2, 2015, 9:51:10 PM2/2/15
to cn-cl...@googlegroups.com
 在使用宏的时候  有unqualified symbol   概念,不是很清楚

想知道下
(defmacro m [] `(let [x# 1] x#))   与 (defmacro m [] `(let [~'x 1] ~'x))  的区别;  
 

Robert Luo

unread,
Feb 2, 2015, 11:08:13 PM2/2/15
to cn-cl...@googlegroups.com
x# 相当于 gensym 函数调用后的结果,让 reader 给你制造一个新的命名,你用 macroexpand-1 看看结果就知道,第一种写法的实际结果是:

(macroexpand-1 '(m))
=> (clojure.core/let [x__12287__auto__ 1] x__12287__auto__)

而第二种写法就只不过是:
(macroexpand-1 '(m))
=> (clojure.core/let [x 1] x)

对于这个宏来说,这没有实际区别。毕竟 x 没有在其他地方使用。但如果你通过外部在宏的内容中使用了 x 的话,第二种写法就造成了命名重叠,例如:

(defmacro m [body] `(let [~'x 1] ~body))
(m (inc x))

返回 2。而如果用 x#来写作,由于实际的 symbol 名字外界无从得知,因此是不会互相干扰的。

Xiaojun Weng

unread,
Feb 2, 2015, 11:29:02 PM2/2/15
to cn-cl...@googlegroups.com
nice, 写得很清楚,谢谢!

在 2015年2月3日星期二 UTC+8下午12:08:13,Robert Luo写道:

Jianliu Hu

unread,
Feb 3, 2015, 7:15:18 AM2/3/15
to cn-cl...@googlegroups.com
这种做法很常见的,比如有时候编程要生成临时文件盒临时表的时候,也会采取一些策略避免重复,比如有时候把进程id加在临时文件名字后面。:)

在 2015年2月3日星期二 UTC+8下午12:29:02,Xiaojun Weng写道:
Reply all
Reply to author
Forward
0 new messages