0

I'm facing some problems understanding the results of a few experiments with nconc.

(setf x '(a b c))
(setf y '(1 2 3))

(nconc x y) ; => x = (A B C 1 2 3), y = (1 2 3)

From what I've read, nconc changes the rest field of x to point to y.

(setf (nth 1 y) 10) ; => x = (A B C 1 10 3), y = (1 10 3)

So far, so good.

(setf y '(4 5 6)) ; => x = (A B C 1 10 3) y = (4 5 6)

Why does x still reference to the old cons cell, or in other words does the reassignment of y not just change the data at the address of y?

Thanks in advance Michael

3 Answers 3

4

Lisp variables don't point to fixed memory. They point to Lisp data objects. Setting a variable does not change any object memory. The variable just points to some other data.

Sign up to request clarification or add additional context in comments.

Comments

2

Because the last cons in x is set to pointing to the cons that y was pointing at. It doesn't point at y's value dynamically or by reference.

(setf x '(a b c))
; x = (a b c)
(setf y '(1 2 3))
; x = (a b c)
; y = (1 2 3)
(nconc x y)
; x = (a b c 1 2 3)
; y = (1 2 3) = (nthcdr 3 x)
(setf (nth 1 y) 10)
; x = (a b c 1 10 3)
; y = (1 10 3) = (nthcdr 3 x)
(setf y '(4 5 6))
; x = (a b c 1 10 3)
; y = (4 5 6)

Comments

0

nconc changes the rest field of x to point to the value of y. The value y is the cell, which y points to. If you move the y pointer to another target, the rest field of x won't change, and will still point to (1 2 3).

3 Comments

Thank you for your answer (both of you) I think "if you move the pointer.. " got me in the right direction. If I understand correctly: setf on a symbol does not change existing data - even if the symbol already exists, but always creates a new memory location to store the value. Only setf to a cons cell will overwrite existing data in memory. Correct?
No, that's not quite right. Actually setf is change existing data. And in case (setf x ...) it changes the value of x, not *x (the value, pointed by x) in C-notation.
Thank you, that's what I meant - sorry my comment wasn't that clear. It sure changes the value of the 'pointer'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.