Having trouble with clojure macro
I'm trying to write a macro that I can use to call a function on a new thread and print the name of the function as well as the name of the thread after running it.
So far what I have is:
(defmacro start-threads [f]
'(let [t (Thread. 'f)]
(prn (str "running " 'f " on: " (.getName t)))))
which when I run:
(start-threads funcname)
outputs: "running f on: Thread-47". and I would like it to output: "running funcname on: Thread-47. When I try unquoting it it try's to evaluate the function. I know I haven't run .start on the thread here, but I should be able to add that in afterward. I'm sure a macro isnt completely necessary here, I'm mostly wondering out of curiosity as I am just starting to wrap my mind around how macros in clojure work.
Basically, what you want is syntax-quote rather than normal quote.
(defmacro start-threads [f]
`(let [t# (Thread. ~f)]
(prn (str "running " '~f " on: " (.getName t#)))))
~f
in a syntax-quote interpolates the value of f
, '~f
quotes that value and the t#
makes an auto-gensym so the variable name won't conflict with any surrounding names.
But as you correctly note, you really don't need a macro for this. It could easily be a function:
(defn start-threads [f]
(let [t (Thread. f)]
(prn (str "running " f " on: " (.getName t)))))
链接地址: http://www.djcxy.com/p/65760.html
上一篇: clojure引号和宏代码中的代字符
下一篇: 与clojure宏有困难