开发者

Strange behaviour of keywords within macros in Clojure

开发者 https://www.devze.com 2022-12-31 21:04 出处:网络
I\'m a little confused by how keyword accesses seem to behave in Clojure when they are evaluated at macro expansion time.开发者_运维技巧

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

精彩评论

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