Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic and Lexical variables in Common Lisp
    text
    copied!<p>I am reading the book 'Practical Common Lisp' by Peter Seibel.</p> <p>In Chapter 6, "Variables" sections "Lexical Variables and Closures" and "Dynamic, a.k.a. Special, Variables". <a href="http://www.gigamonkeys.com/book/variables.html" rel="noreferrer">http://www.gigamonkeys.com/book/variables.html</a></p> <p>My problem is that the examples in both sections show how (let ...) can shadow global variables and doesn't really tell the difference between the Dynamic and Lexical vars.</p> <p>I understand how closures work but I don't really get whats so special about let in this example:</p> <pre><code>(defvar *x* 10) (defun foo () (format t "Before assignment~18tX: ~d~%" *x*) (setf *x* (+ 1 *x*)) (format t "After assignment~18tX: ~d~%" *x*)) (defun bar () (foo) (let ((*x* 20)) (foo)) (foo)) CL-USER&gt; (foo) Before assignment X: 10 After assignment X: 11 NIL CL-USER&gt; (bar) Before assignment X: 11 After assignment X: 12 Before assignment X: 20 After assignment X: 21 Before assignment X: 12 After assignment X: 13 NIL </code></pre> <p>I feel like there is nothing special is going on here. The outer <em>foo</em> in <em>bar</em> increments the global <em>x</em>, and <em>foo</em> surrounded by <em>let</em> in <em>bar</em> increments the shadowed <em>x</em>. What's the big deal? I don't see how is this supposed to explain the difference between lexical and dynamic vars. Yet the book continues like this:</p> <blockquote> <p>So how does this work? How does LET know that when it binds <em>x</em> it's supposed to create a dynamic binding rather than a normal lexical binding? It knows because the name has been declared special.12 The name of every variable defined with DEFVAR and DEFPARAMETER is automatically declared globally special.</p> </blockquote> <p>What whould happen if <em>let</em> would bind <em>x</em> using <strong>"normal lexical binding"</strong>? All in all, what are the differences between dynamic and lexical binding and how is this example special regarding dynamic binding?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload