How do I get the argument in a macro from a map macro in Clojure?

久未见 提交于 2019-12-13 17:57:06

问题


I'm passing my macro to a map operation (which is also a macro). I'm having some trouble getting my values out. Here is an example:

(def num-vec [1 2 3 4 5])

(defmacro describe-args [first-arg & remaining-args]
  `(println '~first-arg '~remaining-args))

(doall (map #(describe-args "my args " %) num-vec))

This returns:

  my args  (p1__432#)
  my args  (p1__432#)
  my args  (p1__432#)
  my args  (p1__432#)
  my args  (p1__432#)

My question is: How do I get the argument in a macro from a map macro in Clojure?

(I believe this is a different question to the other map/macro questions already asked as this is about argument retrieval).


回答1:


You can change macro describe-args to:

(defmacro describe-args [desc & args]
  `(println ~desc ~@args))

Now

(doall (map #(describe-args "my args " %) num-vec))

prints

my args  1
my args  2
my args  3
my args  4
my args  5

More general debugging macro is described in this answer.




回答2:


Not sure if this is you want

(defmacro print-second [form]
  (if (list? form) 
     `(do (println '~(second form) " = " ~(second form)) ~form)
     form))

(def num-vec [1 2 3 4 5])

(doall (map #(print-second (+ (* 3 42) %)) num-vec))

=>

;(* 3 42)  =  126
;(* 3 42)  =  126
;(* 3 42)  =  126
;(* 3 42)  =  126
;(* 3 42)  =  126
(127 128 129 130 131)


(print-second (+ 99 7))

=>

;99  =  99
106

(print-second 3)

=>

3


来源:https://stackoverflow.com/questions/28539818/how-do-i-get-the-argument-in-a-macro-from-a-map-macro-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!