简体   繁体   中英

Macro quoting and unquoting

I'm trying to write a macro to require some namespaces programmatically, so that the result for a passed-in argument would be (require 'value-of-argument) . If I say (defmacro r [x] `(require ~x)) then I get (require value-of-x) as expected, but I can't work out how to get the quote in there.

Edit: here's a simpler example of my problem:

(defmacro q [x] `(str ~x))

=> (map (fn [e] (q e)) (map symbol ["x" "y" "z"]))
=> ("x" "y" "z")

however,

(defmacro q [x] `(str '~x))

=> (map (fn [e] (q e)) (map symbol ["x" "y" "z"]))
=> ("e" "e" "e")

All you need is to quote the argument again, like this:

(defmacro r [x] `(require '~x))

It should do the trick.

EDIT: The above won't work since x isn't known at compile time, when the macro is expanded.

However, now that I think about it, why not just call require directly, without a macro?

This seems to work:

(require (symbol "clojure.walk"))

Does that help?

(defmacro r [x] `(require (quote ~x)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM