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

Question

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

Answers 2
Added at 2017-01-05 20:01
Tags
Question

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?

Answers
nr: #1 dodano: 2017-01-05 20:01

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.

nr: #2 dodano: 2017-01-07 17:01

Here's some examples that might clarify this. You can try them at the repl. Try to think about whether they are more like defvar or defparameter

(loop repeat 2 do
  (let ((a 1)) (print a) (setf a 5) (print a)))

(loop repeat 2 do
  (let ((a (list 1 2)))
    (print (first a))
    (setf (first a) 5)
    (print (first a))))

(loop repeat 2 do
  (let ((a '(1 2)))
    (print (first a))
    (setf (first a) (+ (first a) 5))
    (print (first a))))

Hopefully these examples should help you get a better idea of what let does. What happens when you put the third example into the repl is actually implementation dependant and has little to do with let and much more to do with quote.

Source Show
◀ Wstecz