3 ms·
Correct. (let* ((x '(a b c)) (y (cdr x)) (z (copy-list (cdr x)))) (format t "y=~A, z=~A~%" y z) (setf (nth 1 x) 'w) (format t "
by kagevf 2y ago
Correct.
(let* ((x '(a b c))
(y (cdr x))
(z (copy-list (cdr x))))
(format t "y=~A, z=~A~%" y z)
(setf (nth 1 x) 'w)
(format t "y=~A, z=~A~%" y z))
=>
y=(B C), z=(B C)
y=(W C), z=(B C)
- trealira 2y agoJust so you know, modifying quoted lists in Lisp is not dissimilar to setting string literals in C: it's undefined behavior, i.e., it's not guaranteed to work, or be portable if it does work, and it may or may not make your program behave strangely if it does work. To make a mutable list, you could write (list a b c).
- kagevf 2y agoYes, updating literals is asking for trouble, or at least can lead to some confusion. If I replace ‘(a b c) in my example with (list ‘a ‘b ‘c) I got the same results.
- trealira 2y ago> If I replace ‘(a b c) in my example with (list ‘a ‘b ‘c) I got the same results. Yeah, your core point was right, just thought to let you know about that bit of undefined behavior.
- kagevf 2y agoI think you made a worthwhile point. I recall seeing either on IRC or reddit someone asking about why their code wasn't working as expected, and it lead back to needing to understand that the string literal in their code was getting updated - so likely similar to the UB in C that you mentioned. Until seeing that post, I wasn't really aware of that potential issue with literals, so I think it's good to point these things out. Recently, I saw it was mentioned in "Successful Lisp"; it might be mentioned in other books I've read, but maybe I just didn't pick up on it.