title: Lexical versus dynamic scope, let form, declare form
body: <p>Dynamic versus lexical scope.    </p>
  
  <pre><code>; One expects lexical scope.    
  (let (( a '(a))) 
    (defun func1 (x)
      (setq a (cons x (cons (func2 x) a))))
    (defun func2 (y) 
      (setq a (cons y a))))
  
  (func1 'b)
  =&gt; (B (B A) B A)
  </code></pre>
  
  <p>Doing it lexically, one would expect
  the following.</p>
  
  <ol>
  <li>Substitute <code>(a)</code> for the <code>a</code> in <code>func2</code>.</li>
  <li><code>func2</code> is called with <code>x</code>, i.e. the value <code>b</code>.</li>
  <li><code>func2</code> also attaches the value of <code>a</code> with <code>(a)</code>.</li>
  <li>So the <code>(cons y a)</code> evaluates to <code>(b a)</code>.</li>
  <li><code>(setq a (cons y a)))</code> is <code>(b a)</code>.</li>
  <li>So <code>func1</code> will cons <code>(b a)</code> with <code>(a)</code>.</li>
  <li><code>x</code> is then consed <code>(b (b a) a))</code>.</li>
  <li>End result <code>(b (b a) a)</code>?  Is this a contradiction?</li>
  </ol>
  
  <p>Let us try a dynamical version.
      ; dynamic scope</p>
  
  <pre><code>(defparameter a '(a)) 
  
  (defun func1 (x)
    (setq a (cons x (cons (func2 x) a))))
  
  (defun func2 (y) 
    (setq a (cons y a)))
  
  (func1 'b)
  =&gt;(B (B A) B A)
  </code></pre>
  
  <p>This works as is to be expected but is the same as in lexical scope?</p>
  
  <p>But the following is not accepted at all.</p>
  
  <pre><code>; This won't work.
  (let (( a '(a))) 
    (defun func1 (x)
      (declare (special a)) 
      (setq a (cons x (cons (func2 x) a))))
    (defun func2 (y) 
      (declare (special a))
      (setq a (cons y a))))
  
  (func1 'b)
  Error: Attempt to take the value of the unbound variable `A'.   
  </code></pre>
  
  <p>What is going on?  </p>