O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Macros

To see how, we’ll need to understand Clojure’s macro system. A macro is a special kind of function. It’s intended to take a piece of data that represents code, also known as a form. A macro transforms one form into another before Clojure’s compiler compiles it. Finally, the evaluation rule for a macro is special in that a macro does not evaluate its arguments.

Let’s take a look at a simple macro. This macro takes two arguments, a name and a string to print. It then creates a function that prints the passed-in string.

 (​defmacro​ make-printer [name to-print]
  (list ​'defn​ name [] (list ​'println​ to-print)))

Here we’ll use it to create a function named foo.

 => (make-printer foo "this is a foo")
 #'matters/foo
 => (foo)
 this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required