Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Macros and Protocols

Macros: The Basics

Learn what Clojure macros are and how to write them: code as data, defmacro, quote, syntax quote, unquote, unquote-splicing and macroexpand with clear examples.

In Clojure, code is written in the same data structures the language manipulates: lists, vectors, symbols and keywords. This property is called homoiconicity, and it makes macros possible. A macro is a function that runs at compile time: it receives code as data, builds new code as data, and the compiler then compiles that result in place of the original form.

You already use macros all the time: when, cond, ->, ->>, defn, and, or, doseq and for are macros. Knowing how they work removes a lot of mystery, and lets you add your own syntax when a function cannot do the job.

Why functions are not enough

A function evaluates all its arguments before it runs. That makes it impossible to write your own if-like construct as a function.

CLOJURE
(defn my-unless [test body]
  (if test nil body))

(my-unless true (println "never printed?"))
; prints, because (println ...) was evaluated BEFORE my-unless was called

You need control over when and whether the arguments are evaluated. A macro receives the unevaluated forms.

Your first macro

CLOJURE
(defmacro unless [test & body]
  (list 'if test nil (cons 'do body)))

(unless false
  (println "runs")
  :done)
;; prints "runs", returns :done

(unless true (println "skipped"))   ;=> nil, nothing printed

unless receives test and body as unevaluated code. It returns the list (if test nil (do ...)), which the compiler then compiles instead. The quote 'if makes the symbol if appear literally in the output instead of being evaluated as a variable.

Inspecting what a macro does

macroexpand-1 expands a form one step; macroexpand expands the head repeatedly until it is no longer a macro call.

CLOJURE
(macroexpand-1 '(unless false (println "hi") :done))
;=> (if false nil (do (println "hi") :done))

(macroexpand-1 '(when x a b))
;=> (if x (do a b))

When a macro misbehaves, expand it first; the bug is nearly always visible in the generated code. Many editors have a "macroexpand" key.

Quote, syntax quote and unquote

Building code with list and cons gets painful. Clojure provides a template syntax for macros.

  • 'x (quote) means "this symbol or list, as data, unevaluated".
  • `x (syntax quote) is quote with two extras: symbols are namespace-qualified (so if is if, inc becomes clojure.core/inc), and it allows unquoting.
  • ~x (unquote) evaluates x and inserts the result into the template.
  • ~@x (unquote-splicing) evaluates x (a sequence) and splices its items in.
CLOJURE
(defmacro unless [test & body]
  `(if ~test nil (do ~@body)))

Read it as a template: the shape of the generated code is visible, and only the parts marked with ~ are filled in. Compare how each marker behaves:

CLOJURE
(let [x 5, xs [1 2 3]]
  [`(a ~x)       ;=> (user/a 5)
   `(a ~xs)      ;=> (user/a [1 2 3])
   `(a ~@xs)])   ;=> (user/a 1 2 3)

Because syntax quote qualifies symbols, you avoid accidentally capturing a user's local names, which the next lesson covers in depth.

A few more examples

A time-it macro measures any code without wrapping it in a function:

CLOJURE
(defmacro time-it [label & body]
  `(let [start# (System/nanoTime)
         result# (do ~@body)]
     (println ~label (/ (- (System/nanoTime) start#) 1e6) "ms")
     result#))

(time-it "sum" (reduce + (range 1000000)))

Names ending in # (like start#) are auto-gensyms: Clojure replaces each with a unique symbol so it cannot clash with the caller's variables.

A my-and shows why macros can short-circuit:

CLOJURE
(defmacro my-and
  ([] true)
  ([x] x)
  ([x & more] `(let [t# ~x] (if t# (my-and ~@more) t#))))

(my-and 1 2 nil (println "never"))   ;=> nil

Each argument is evaluated only if the earlier ones were truthy, which no function could do.

Rules of thumb

  1. Do not write a macro when a function will do. Macros cannot be passed to map or apply, are harder to read and debug, and compose poorly.
  2. Use a macro when you need to control evaluation (conditionals, loops), add new binding forms, remove boilerplate that functions cannot, or create definitions (like defn).
  3. Keep the macro thin: have it expand into a call to a regular function, and put the logic in the function.
  4. Always test with macroexpand-1.

Try it: code as data, in JavaScript

We cannot run Clojure here, but the key idea, that a macro is a function from code-data to code-data, is easy to show. Below, forms are nested arrays, unless is a function that rewrites a form, and a tiny evaluator then runs it.

JS A macro as a rewrite function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: syntax quote templating

This stand-in imitates ~ and ~@ with a template function, so you can see how splicing flattens a sequence into the surrounding list.

JS Unquote and splice

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a macro run?

    Macros receive code as data and return code, before the program runs.
  2. 2. What does ~@body do in a syntax-quoted template?

    Unquote-splicing evaluates body (a sequence) and inserts its elements individually.
  3. 3. Why can't unless be an ordinary function?

    A macro receives unevaluated forms and can decide whether to evaluate them.
  4. 4. How do you inspect what a macro call expands to?

    macroexpand-1 returns the one-step expansion; macroexpand repeats until the head is not a macro.

Summary

  • Code is data in Clojure, so a macro is a compile-time function from forms to forms.
  • Use defmacro; a macro receives unevaluated arguments and returns the code to compile.
  • Syntax quote (backtick) makes templates; ~ inserts a value, ~@ splices a sequence, x# makes unique names.
  • Expand with macroexpand-1 to debug.
  • Prefer functions; use macros for control over evaluation, new syntax and boilerplate.

Next: Writing Better Macros