Search code examples
lispcommon-lisplet

Is the variable defined by a let mutable in Common Lisp?


In, for example this let in Common Lisp

(let ((a 5)) (print a))

Is a mutable as with defparameter, or is a constant as is the case with defvar?


Solution

  • You can change what a is bound to, i.e. make a refer to something else:

    (let ((a 5)) (setf a 10))
    

    If the value referenced by a is mutable, you can mutate it:

    (let ((a (list 5))) (setf (first a) 10))
    

    Is a mutable as with defparameter, or is a constant as is the case with defvar?

    No, DEFVAR does not define constants.

    (defvar *var* :value)
    (setf *var* 5)
    

    Then:

    *var*
    => 5
    

    What happens is that when you evaluate a DEFVAR form, it first checks whether the symbol is already bound. If this is the case, then the existing value is kept in place. On the other hand, DEFPARAMETER always reintializes the variable.