How to copy a list, not share a structure?

Wow, I totally don't understand this bit!

I have a list, L1 . I want to make a copy of L2 so that when L2 changes, L1 remains unchanged. I thought for copy-seq , but it does not behave as expected.

 (defun tcopy () (let ((seq1 nil) (seq2 nil)) (setf seq1 (list (list 11 22) (list 33 44 55))) (setf seq2 (copy-seq seq1)) (format t "before -- s1: ~a s2: ~a~%" seq1 seq2) (setf (nth 1 (nth 1 seq2)) 99) (format t "after -- s1: ~a s2: ~a~%" seq1 seq2))) 

And the conclusion:

 ? (tcopy) before -- s1: ((11 22) (33 44 55)) s2: ((11 22) (33 44 55)) after -- s1: ((11 22) (33 99 55)) s2: ((11 22) (33 99 55)) ; Undesired: s1 is modified NIL ? 

I also tried the following:

 ;(setf seq2 (copy-seq seq1)) (setf seq2 (reduce #'cons seg1 :from-end t :initial-value nil)) 

He gives the same results. Lisp -n00b, here; what am I missing ?!

Thanks!

+4
source share
1 answer

COPY-SEQ copies only the top-level sequence. Not a subsequence. ( COPY-LIST behaves the same.)

COPY-TREE copies the cons cell tree. In this way, it will also copy lists of lists of lists ...

+11
source

Source: https://habr.com/ru/post/1496460/


All Articles