开发者

Strange behaviour of keywords within macros in Clojure

I'm a little confused by how keyword accesses seem to behave in Clojure when they are evaluated at macro expansion time.

开发者_运维技巧

The following works as I expect:

(def m {:a 1})
(:a m)
=> 1 

However the same keyword access doesn't seem to work within a macro:

(def m {:a 1})
(defmacro get-a [x] (:a x))
(get-a m)
=> nil

Any idea what is going on here?


You should take into account that macro's don't evaluate their arguments, unless you tell them so. In your version, get-a gets a symbol m and the result isn't code, it is keyword :a looking itself up in a symbol, which is obviously nil. This works however:

(defmacro get-a [x] `(:a ~x))

The result of calling this macro with argument m is the expression '(:a m)', which evaluates to 1 in your context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜