Strange Macro Keyword Behavior in Clojure

I'm a little confused about how the behavior of the keywords appears to behave in Clojure when they are computed when the macro expands.

The following works as I expect:

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

However, the same keyword access does not work in a macro:

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

Any idea what is going on here?

+4
source share
1 answer

You must bear in mind that a macro does not evaluate its arguments unless you tell them about it. In your version, get-a receives the character m, and the result is not code, this is the keyword: a looks for itself in the character, which is obviously zero. However, this works:

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

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

+8
source

Source: https://habr.com/ru/post/1310288/


All Articles