1

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).

hawkeye
  • 34,745
  • 30
  • 150
  • 304

2 Answers2

2

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.

Community
  • 1
  • 1
Jarlax
  • 1,586
  • 10
  • 20
  • 2
    `'~desc` - the `'` (quote) is not needed here. It is expanding to `(quote "my args ")` – Kyle Feb 16 '15 at 15:00
0

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
Changgeng
  • 578
  • 2
  • 8
  • That's awesome. Here is a harder one: http://stackoverflow.com/questions/28645530/how-do-i-get-the-nested-argument-in-a-macro-inside-a-mapped-function-in-clojure – hawkeye Feb 22 '15 at 03:55