Re: gensym in macro definition



Guybrush Threepwood wrote:
(defmacro n-of (n expression)
(let ((i (gensym)))
`(loop for ,i from 1 to ,n
collect ,expression)))

I wonder if the gensym is really necessary.

Yes it is, since the loop variable is in the scope of the expression.
If you just call it X, and the expression contains a reference to X,
that reference will go to that X instead of the one the programmer
wants to reach:

(defmacro n-of (n expression)
`(loop for x from 1 to ,n
collect ,expression))

(let ((x 42))
(n-of 10 x))

-> (1 2 3 4 5 6 7 8 9 10) ; surprise!!!

Have you considered actually trying it both ways? One way to
demonstrate that the gensym is needed is not to put one in, and then
show a miscalculation like the above.

.