1

Why, when I use nth to change a list element, do all elements change?

(setq mlist nil)
(loop for aa from 1 to 10 
    do
        (setq mlist (append mlist (list '(0 2))))
)
(print mlist)
(setf (nth 0 (nth 0 mlist)) 9)
(print mlist)

Expected result:

((9 2) (0 2) (0 2) (0 2) (0 2) (0 2) (0 2) (0 2) (0 2) (0 2))

Result I got:

((9 2) (9 2) (9 2) (9 2) (9 2) (9 2) (9 2) (9 2) (9 2) (9 2))
Ehvince
  • 17,274
  • 7
  • 58
  • 79
csisman
  • 11
  • 1
  • 1
    https://stackoverflow.com/a/578365/1848654 – melpomene Aug 25 '19 at 04:55
  • 2
    Your program contains only one `(0 2)` list. It's a piece of that program itself. When a program uses a piece of itself as a datum, that's a "literal". If you evaluate the same piece two or more times, you get the same object: the same piece of the program. – Kaz Aug 26 '19 at 06:47
  • 1
    @Xanthir's answer there says: The HyperSpec clhs.lisp.se/Body/s_quote.htm says behavior is undefined if the quoted object is destructively modified. It's implied that this is to allow impls to treat the values as atomic values - your '(0 2) is a quoted object. – Gwang-Jin Kim Aug 27 '19 at 02:10
  • change the inner `(list '(0 2))` to `(list (list 0 2))` - then it behaves as you want! – Gwang-Jin Kim Aug 27 '19 at 02:13
  • Also see https://stackoverflow.com/q/18790192/1281433 – Joshua Taylor Aug 30 '19 at 17:38

0 Answers0