Chapter 8. Macros
ClojureScript, like Clojure, uses macros to extend the syntax of the language. Fundamentally, a macro is just a function that manipulates data structures. What makes macros special is that they are invoked during the compilation process, to manipulate the data structures representing ClojureScript source code. Many of ClojureScript’s core flow-control operators are implemented as macros, and you can write your own macros to extend the language.
Code as Data
Remember from Chapter 4 that all ClojureScript code is composed of data structures: lists, vectors, symbols, and so on. For example:
(println "Three plus four is" (+ 3 4))
We can read this expression as a list containing a symbol, a string, and another list. But to the ClojureScript compiler, that list represents a function call.
Macros allow you to manipulate the data structures in your code before they get to the compiler. This is very powerful: a macro can effectively rewrite code before it gets to the compiler.
Writing Macros
Macros are applied during the compilation process. They do not exist at runtime. Because the ClojureScript compiler is implemented in Clojure, ClojureScript macros must be written in Clojure, not ClojureScript. Fortunately, Clojure and ClojureScript are almost identical when it comes to manipulating data structures, so switching between the two languages is not difficult.
As an example, consider the when
macro introduced in
Chapter 4:
(when condition
;; ... expressions ...
) ;; which expands ...
Get ClojureScript: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.