4 ms·
eval and macros both deal with code-as-data (homoiconicity), but they serve very different purposes and work at different times in the program lifecycle: eval
by andsoitis 1y ago
eval and macros both deal with code-as-data (homoiconicity), but they serve very different purposes and work at different times in the program lifecycle:
eval
Runs at runtime.
Takes a data structure (usually a list) and evaluates it as Lisp code.
Example: (eval '(+ 1 2)) ; => 3
Use case: Dynamically construct and run code while the program is running.
Macros
Runs at compile time (or macro-expansion time).
Transform Lisp code before it's evaluated. They return new code (a Lisp form) to be compiled/evaluated later.
Example:
(defmacro my-unless (condition body)
`(if (not ,condition) ,body))
(my-unless (= 1 2) (print "Not equal")) ; expands to (if (not (= 1 2)) (print ...))
Use case: Extend the language by defining new syntactic constructs. Enables powerful DSLs and optimizations.