"* (macroexpand '(nif x 'pos 'zero 'neg)) (LET ((#:G1605 X)) (COND ((PLUSP #:G1605)…
- User
"* (macroexpand '(nif x 'pos 'zero 'neg))
(LET ((#:G1605 X)) (COND ((PLUSP #:G1605) 'POS) ((ZEROP #:G1605) 'ZERO) (T 'NEG))) T
The name g disappears in the macro expansion. Because g was only bound in our expander environment, the name given to such a variable is irrelevant with respect to capture in the expansions. All occurrences of g have, in the expansion, been replaced by a symbol with a print name of G1605. It is prefixed by #: because the symbol is not interned in any package—it is a gensym. When printing out forms, it is necessary to prefix gensyms in such a way because we want lisp to break if we ever use (evaluate) this form after reading it back in again. We want lisp to break because we can't know by looking at the print names of two gensyms if they should be eq or not—that is their purpose. Lisp breaks in an interesting way: because each time a #: symbol is read in a new symbol is created, and because (eq '#:a '#:a) is never true, the inner #:G1605 symbols in the above expansion do not refer to the binding created by the let form so lisp considers the expression to have a free variable, indicating to us that a form with gensyms was read back in again." explain : "...We want lisp to break because we can't know by looking at the print names of two gensyms if they should be eq or not..."
- Assistant
In Lisp, a gensym is a symbol generated in such a way that it is guaranteed to be unique. This is useful in avoiding name clashes, particularly in macro expansions where unintentional variable capture can occur.
When Lisp generates a gensym, it ensures that each invocation of the gensym function results in a completely new and distinct symbol. Two different gensyms with the same print name (e.g.,
#:G1605) are not considered the same because they are distinct symbols, meaning they are noteq—a Lisp predicate that checks if two symbols refer to the exact same thing in memory.The reason we want Lisp to "break" or alert us when it encounters unresolved gensyms in a re-read form is tied to this property: we can't determine from their print names alone if two gensyms are supposed to refer to the same logical entity. If we were to read the printed form back into our Lisp program, the gensyms could effectively lose their original intended unique identity. Reconstructing or re-reading gensyms, therefore, risks losing the association between identical names and their unique objects in memory. This is why a Lisp interpreter will signal an error if gensyms are used in situations requiring them to be —it is a safeguard to inform the programmer that reevaluating the expression might lead to incorrect assumptions about symbol identity.