Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 954
mikera Avatar asked Feb 27 '23 00:02

mikera


1 Answers

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.

like image 177
Michiel Borkent Avatar answered Mar 07 '23 17:03

Michiel Borkent