liveBook · Manning

Macro

As explained in Clojure: The Essential Reference

A macro is a program construct that transforms unevaluated source forms before they are evaluated.

A macro transforms unevaluated source forms before evaluation. In Clojure, a macro is a regular function invoked by the compiler: it receives its arguments as implicitly quoted data and returns a valid Clojure expression for runtime evaluation. section 4.0

Macros are useful when ordinary functions cannot express the desired syntax or evaluation flow:

  • Reduce repeated code and express operations more concisely. section 4.0
  • Alter normal evaluation flow, as threading macros do when describing processing pipelines. section 2.5 section 2.0
  • Support complex domain-specific languages or embedded compilers. section 4.0

Creating and inspecting a macro

Use defmacro as the main definition entry point. Use quote when a form must remain unevaluated, and macroexpand to inspect the expression produced by a macro without executing it. Use gensym when generated code needs unique symbol names. section 4.0 section 4.9

Macro programming combines code and data: the macro receives forms, constructs a replacement form, and leaves that result for runtime evaluation. Its power comes with special syntax that can initially make macros harder to understand. section 4.0 section 4.9

How Clojure: The Essential Reference covers it

How deep it goes
Explains definition, expansion, quoting, hygiene, and debugging tools, while deferring detailed implementation examples.
Examples
Uses threading macros, defmacro, macroexpand, quote, apply-template, do-template, gensym, and destructuring as representative facilities.
What it assumes
Assumes familiarity with Clojure functions and builds on homoiconic code-as-data manipulation.
What you can do after
Build it from scratch with defmacro, inspect expansions with macroexpand, preserve forms with quote, and generate unique names with gensym.
How it connects
Connects macros with functions, compiler evaluation, quote, macroexpand, syntax-quote, gensym, destructuring, and threading macros.

Also explained in

Compare how 9 books explain macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.