Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setq and defvar in Lisp

I see that the Practical Common Lisp uses (defvar *db* nil) for setting up a global variable. Isn't it OK to use setq for the same purpose?

What are the advantages/disadvantages of using defvar vs. setq?

like image 363
prosseek Avatar asked Oct 04 '10 13:10

prosseek


People also ask

What is Defparameter in Common Lisp?

DEFPARAMETER defines global variable with dynamic scoping. Usual conventions dictate to make such variables easy to distinguish so their name is surrounded by stars. Value for variable is reevaluated for each occurence (unlike with DEFVAR).

How do you assign a value to a variable in Lisp?

valn are the initial values assigned to the respective variables. When let is executed, each variable is assigned the respective value and lastly the s-expression is evaluated. The value of the last expression evaluated is returned. If you don't include an initial value for a variable, it is assigned to nil.

What is let * In Lisp?

The let expression is a special form in Lisp that you will need to use in most function definitions. let is used to attach or bind a symbol to a value in such a way that the Lisp interpreter will not confuse the variable with a variable of the same name that is not part of the function.

How do you declare a global variable in Lisp?

Defining a global variable: New global variables can be defined using DEFVAR and DEFPARAMETER construct. The difference between both of them is that DEFPARAMETER always assigns initial value and DEFVAR form can be used to create a global variable without giving it a value.


2 Answers

There are several ways to introduce variables.

DEFVAR and DEFPARAMETER introduce global dynamic variables. DEFVAR optionally sets it to some value, unless it is already defined. DEFPARAMETER sets it always to the provided value. SETQ does not introduce a variable.

(defparameter *number-of-processes* 10)  (defvar *world* (make-world))     ; the world is made only once. 

Notice that you likely never want to DEFVAR variables with names like x, y, stream, limit, ... Why? Because these variables then would be declared special and its difficult to undo that. The special declaration is global and all further uses of the variable would use dynamic binding.

BAD:

(defvar x 10)     ; global special variable X, naming convention violated (defvar y 20)     ; global special variable Y, naming convention violated  (defun foo ()   (+ x y))        ; refers to special variables X and y  (defun bar (x y)  ; OOPS!! X and Y are special variables                   ; even though they are parameters of a function!   (+ (foo) x y))  (bar 5 7)         ; ->   24 

BETTER: Always mark special variables with * in their names!

(defvar *x* 10)     ; global special variable *X* (defvar *y* 20)     ; global special variable *Y*  (defun foo ()   (+ *x* *y*))      ; refers to special variables X and y  (defun bar (x y)    ; Yep! X and Y are lexical variables   (+ (foo) x y))  (bar 5 7)           ;  ->   42 

Local variables are introduced with DEFUN, LAMBDA, LET, MULTIPLE-VALUE-BIND and many others.

(defun foo (i-am-a-local-variable)    (print i-am-a-local-variable))  (let ((i-am-also-a-local-variable 'hehe))   (print i-am-also-a-local-variable)) 

Now, by default the local variables in above two forms are lexical, unless they are declared SPECIAL. Then they would be dynamic variables.

Next, there are also several forms to set a variable to new values. SET, SETQ, SETF and others. SETQ and SETF can set both lexical and special (dynamic) variables.

It is required for portable code that one sets variables that are already declared. The exact effect of setting a not declared variable is undefined by the standard.

So, if you know what your Common Lisp implementation does, you can use

(setq world (make-new-world)) 

in the Read-Eval-Print-Loop at the toplevel. But don't use it in your code, since the effect is not portable. Typically SETQ will set the variable. But some implementation might also declare the variable SPECIAL when it doesn't know it (CMU Common Lisp does that by default). That's almost always not what one would want. Use it for casual use if you know what you do, but not for code.

Same here:

(defun make-shiny-new-world ()   (setq world (make-world 'shiny))) 

First, such variables should be written as *world* (with the surrounding * characters), to make clear that it is a global special variable. Second, it should have been declared with DEFVAR or DEFPARAMETER before.

A typical Lisp compiler will complain that above variable is undeclared. Since global lexical variables don't exist in Common Lisp, the compiler has to generate code for a dynamic lookup. Some compiler then say, okay, we assume that this is a dynamic lookup, let's declare it to be special - since that is what we assume anyway.

like image 148
Rainer Joswig Avatar answered Sep 22 '22 03:09

Rainer Joswig


defvar introduces a dynamic variable while setq is used to assign a value to a dynamic or lexical variable. The value of a dynamic variable is looked up in the environment that calls the function, while the value of a lexical variable is looked up in the environment where the function was defined. The following example will make the difference clear:

;; dynamic variable sample > (defvar *x* 100) *X* > (defun fx () *x*) FX > (fx) 100 > (let ((*x* 500)) (fx)) ;; gets the value of *x* from the dynamic scope. 500 > (fx) ;; *x* now refers to the global binding. 100  ;; example of using a lexical variable > (let ((y 200))    (let ((fy (lambda () (format t "~a~%" y))))      (funcall fy) ;; => 200      (let ((y 500))        (funcall fy) ;; => 200, the value of lexically bound y        (setq y 500) ;; => y in the current environment is modified        (funcall fy)) ;; => 200, the value of lexically bound y, which was                       ;; unaffected by setq      (setq y 500) => ;; value of the original y is modified.      (funcall fy))) ;; => 500, the new value of y in fy's defining environment. 

Dynamic variables are useful for passing around a default value. For instance, we can bind the dynamic variable *out* to the standard output, so that it becomes the default output of all io functions. To override this behavior, we just introduce a local binding:

> (defun my-print (s)         (format *out* "~a~%" s)) MY-PRINT > (my-print "hello") hello > (let ((*out* some-stream))     (my-print " cruel ")) ;; goes to some-stream > (my-print " world.") world 

A common use of lexical variables is in defining closures, to emulate objects with state. In the first example, the variable y in the binding environment of fy effectively became the private state of that function.

defvar will assign a value to a variable only if it is not already assigned. So the following re-definition of *x* will not change the original binding:

> (defvar *x* 400) *X* > *x* 100 

We can assign a new value to *x* by using setq:

> (setq *x* 400) 400 > *x* 400 > (fx) 400 > (let ((*x* 500)) (fx)) ;; setq changed the binding of *x*, but                           ;; its dynamic property still remains. 500 > (fx) 400 
like image 45
Vijay Mathew Avatar answered Sep 23 '22 03:09

Vijay Mathew