Macros Aren’t Values
The first and most important drawback with macros is that we can’t treat them as values. As principled functional programmers, we’re quite used to thinking about functions as values. For example, we can pass functions as arguments to higher-order functions like map and filter to decouple looping logic from transformation and selection logic. When we use a macro instead of a function, we lose that ability:
beware/not_values_1.clj | |
| user=> (defn square [x] (* x x)) |
| ;=> #'user/square |
| user=> (map square (range 10)) |
| ;=> (0 1 4 9 16 25 36 49 64 81) |
| user=> (defmacro square [x] `(* ~x ~x)) |
| ;=> #'user/square |
| user=> (map square (range 10)) |
| ;CompilerException java.lang.RuntimeException: |
| ; Can't take value ... |
Get Mastering Clojure Macros 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.