title: What is wrong with the following Common Lisp macro using gensym?
body: <p>Learning Common Lisp (using GNU CLISP 2.43) .. so might be a noob mistake. Example is the 'print prime numbers between x and y' </p>
  
  <pre><code>(defun is-prime (n)
    (if (&lt; n 2) (return-from is-prime NIL))
  
    (do ((i 2 (1+ i)))
        ((= i n) T)
      (if (= (mod n i) 0) 
          (return NIL))))
  
  (defun next-prime-after (n)
    (do ((i (1+ n) (1+ i)))
        ((is-prime i) i)))
  
  (defmacro do-primes-v2 ((var start end) &amp;body body)
    `(do ((,var (if (is-prime ,start)
                    ,start
                    (next-prime-after ,start))
                (next-prime-after ,var)))
         ((&gt; ,var ,end))
       ,@body))
  
  (defmacro do-primes-v3 ((var start end) &amp;body body)
    (let ((loop-start (gensym))
          (loop-end (gensym))) 
      `(do ((,loop-start ,start)
            (,loop-end ,end)
            (,var (if (is-prime ,loop-start)
                      ,loop-start
                      (next-prime-after ,loop-start))
                  (next-prime-after ,var)))
           ((&gt; ,var ,loop-end))
         ,@body )))
  </code></pre>
  
  <p>do-primes-v2 works perfectly.</p>
  
  <pre>
  [13]> (do-primes-v2 (p 10 25) (format t "~d " p))
  11 13 17 19 23
  </pre>
  
  <p>Next I tried using gensym to avoid naming clashes in macro expansion - do-primes-v3. However I'm stuck with a </p>
  
  <pre>
  *** - EVAL: variable #:G3498 has no value
  </pre>
  
  <p>Tried using macro-expand to see if i could spot the mistake but I can't.</p>
  
  <pre>
  [16]> (macroexpand-1 `(do-primes-v3 (p 10 25) (format t "~d " p)))
  (DO
   ((#:G3502 10) (#:G3503 25)
    (P (IF (IS-PRIME #:G3502) #:G3502 (NEXT-PRIME-AFTER #:G3502))
       (NEXT-PRIME-AFTER P)))
   ((> P #:G3503)) (FORMAT T "~d " P)) ;
  </pre>