alan2here
alan2here

Reputation: 3317

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?

Upvotes: 0

Views: 477

Answers (2)

Dan Robertson
Dan Robertson

Reputation: 4360

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.

Upvotes: 1

coredump
coredump

Reputation: 38809

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.

Upvotes: 4

Related Questions