This article is the last part of our Clojure macros tutorial. The previous parts were:

  1. functions vs. macros
  2. how not to write macros
  3. syntax quote

Now we are going to show you how clojure ninjas write macros.


The disp macro - by 2 anonymous ninjas

The disp macro receives expressions and returns a symbol with the expressions and their respective evaluations. (A symbol is much more pretty than a string.)


(defn symbol-several
  "returns a symbol with the concatenation of the str values of the args"
  [& x]
  (symbol (apply str x)))

(defmacro disp [& forms]
    (for [form forms]
      `(str '~form " => " ~form "\n"))))

  (map inc [1 2 3])
    (+ 4 5 6))

Two smart guys on Clojurians Slack helped me to write the disp macros.

The defprint macro - by Herwig Hochleitner

The defprint macro defines a function with a tweak: each time the function is called, it prints the values of its arguments. The tricky part is that it works also with desctructuring.


(defmacro defprint [func-name args & body]
  `(defn ~func-name [& args#]
       (print '~func-name "called with: " args#)
            (let [~args args#]

( foo [a b c] (+ a b c))
(foo 1 2 3)

And here is what is printed in when foo is called:

(with-out-str (foo 1 2 3))

Another example, with arguments desctructuring:

( hello-world [& {:keys [language] 
                                  :or {language :en}}]
                                     (case language
                                                        :fr "bonjour monde"
                                                                           :en "hello world"))

(hello-world :language :fr)
(with-out-str (hello-world :language :fr))

And here is the code generated by the macro:

(macroexpand-1 '( foo [& {:keys [language]} :or {language :en}]))

Take a couple of minutes to meditate on the power of this part of the macro:

(let [~args args#]

Herwig Hochleitner helped me to write the defprint macro.

You can read more about desctructuring.

The doseq-indexed macro - by Tim Baldridge

doseq-indexed works like doseq with an additional binding to the index.

Tim Baldridge (core.async author) wrote an elegant implementation for doseq-indexed:


(defmacro doseq-indexed [index-sym [item-sym coll] & body]
  `(doseq [[~item-sym ~index-sym]
             (map vector ~coll (range))]

  ( i [x [10 100 1000]]
                           (println "i: " i "x: " x)))

Here is Tim’s original gist.

Feel free to share your favorite macros in the comments below.

Clojure rocks!