I was surprised to discover that a local variable can have it's state modified across function invocations. Consider the following example.
(defun example-mutable ()
(let ((x '("the" "quick" "brown" "fox")))
(nbutlast x 1)))
nbutlast
is documented as follows:
This is a version of
butlast
that works by destructively modifying the cdr of the appropriate element, rather than making a copy of the list
(And butlast
is a function removes the last n
elements from a list.)
Then multiple calls to example-mutable
will return ("the" "quick" "brown")
, ("the" "quick")
, ("the")
, and nil, in that order.
Another example is the following:
(defun example-nonmutable (change-val)
(let ((x '("the" "quick" "brown" "fox")))
(when change-val
(setq x "something else"))
x))
Then calling (example-nonmutable t)
followed by (example-nonmutable nil)
yields results of "something else"
and ("the" "quick" "brown" "fox")
. So we see that in the first example the value of x
is not rebound on repeat function invocations, while contrastingly in the second example it is rebound.
So I am guessing that when the function is called that Emacs looks at the address of the data that x
is bound to, and if it hasn't been changed, then it doesn't bother to create a new data object and rebind it in the interest of efficiency?
Is this behavior documented in the manual or elsewhere?