User Tools

Site Tools


ch2_1_setq

SETQ

SETQ assigns values to symbols, accepts any number of arguments. The odd (first, third etc.) arguments are not evaled and must be symbols. The even (second, fourth etc.) arguments are evaled and the value is assigned to the symbol. The last set value is returned.

SETQ looks up in the lexical environment for the symbol binding. If local binding is found, the value is rewritten, otherwise the global binding is rewritten. If the symbol is unbound, global binding to the value is created. It is possible to change binding of symbols from the base package, but it can be dangerous. LabLISP informs the user, but sets the value anyway. The SETQ will refuse to set value of a constant.

>(setq a 4)           ; set value of symbol A, globally
4
 
>(setq a 1 b 2 c 3)   ; set value of symbols A B C, globally
3
 
>(setq d 1 e (+ d 1)) ; values are set sequentially
2

The above examples set the global binding of the symbols, but in a program, it is bad style to create global bindings this way. It is cleaner with DEFVAR or DEFPARAMETER.

Example with local variable:

>(let ((a 5))         ; local variable A
    (setq a 6) a)     ; set the local A to 6
6                     ; returned from the LET form
 
>a                    ; access global A
1                     ; value is still 1 from the previous example

It is possible to assign function object or lambda to a symbol, but it will still be stored in the value slot of the symbol, and will not (re)define the symbol as function.

>(defun a (x y) 
     (- x y))         ; define A as subtraction
 
>(setq a #'+)         ; it is possible to assign function object ..
#<function +>         ; .. but it is still in the symbol value 
 
>(a 4 3)              ; call to function A ..
1                     ; .. uses the subtraction

Note that if the odd argument to SETQ is not a symbol, warning will be issued and the form collapses to NIL. However, in a sequence of assignments, the variables assigned before the erroneous one will stay in the environment.

See also: SETF, LET, LET*, DEFVAR, DEFPARAMETER

ch2_1_setq.txt · Last modified: 2022/03/31 06:57 by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki