I have some problem using accessor function nth. I pass a list to some function and make new binding to an element of the list in the function with nth, then when I call the list out of the function, it is modified, and it’s not what I want! What happens?
Some examples
(defun test (x) (incf x)) => TEST
(setq a 1) => 1
(test a) => 2
a => 1
I understand what’s going on above, but if we change everything to lists, something happens that I can’t understand
(defun test (x) (incf (nth 0 x))) => TEST
(setq a '(1)) => (1)
(test a) => 2
a => (2)
I expected a to be (1), why it has been modified? I also tried other functions like car and first, result is the same.
PS, I tried it in Lispworks and SBCL, same result.
You pass
1totest. Within test you modified the local variablex.ais not changed and can’t be changed that way – we pass the value ofanot a reference toa.You pass the list
(1)to test. The list is not copied. The local variablexpoints to the first cons cell in the list. You then modify the car of the first cons cell to 2. Since the list is not copied, you modify the passed list.aalso points to the first cons cell of that list. So it is also(2).