Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

5. Macros > When to Use Macros

When to Use Macros

Macros are clearly a powerful tool, but with that power inevitably comes responsibility—and a list of caveats.

Macros operate at compile time. This means they are not first-class citizens of a running Clojure program like functions are. A macro has no access to runtime information, such as the current runtime values of a var. A macro sees only unevaluated data structures read from source code.

Consider a simple function that returns a greeting. It’s possible to write this as either a function or a macro:

(defn fn-hello [x]
  (str "Hello, " x "!"))

(defmacro macro-hello [x]
  `(str "Hello, " ~x "!"))

These appear to behave similarly in some usages:

(fn-hello "Brian")
;= "Hello, Brian!"
(macro-hello "Brian")
;= "Hello, Brian!"

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial