Dynamic and Lexical variables in Common Lisp

前端 未结 5 1519
予麋鹿
予麋鹿 2020-12-07 16:25

I am reading the book \'Practical Common Lisp\' by Peter Seibel.

In Chapter 6, "Variables" sections "Lexical Variables and Closures" and "Dyn

5条回答
  •  庸人自扰
    2020-12-07 17:24

    When a variable is lexically scoped, the system looks to where the function is defined to find the value for a free variable. When a variable is dynamically scoped, the system looks to where the function is called to find the value for the free variable. Variables in Common Lisp are all lexical by default; however, dynamically scoped variables can be defined at the top level using defvar or defparameter.

    A simpler example

    lexical scoping (with setq):

    (setq x 3)
    
    (defun foo () x)
    
    (let ((x 4)) (foo)) ; returns 3
    

    dynamic scoping (with defvar):

    (defvar x 3)
    
    (defun foo () x)
    
    (let ((x 4)) (foo)) ; returns 4
    

    How does the let know if a variable is lexical or dynamic? It doesn't. On the other hand, when foo goes to find the value of X, it will initially find the lexical value defined at the top level. It then checks to see if the variable is supposed to be dynamic. If it is, then foo looks to the calling environment, which, in this case, uses let to overshadow the value of X to be 4.

    (note: this is an oversimplification, but it will help to visualize the difference between the different scoping rules)

提交回复
热议问题