Re: How to make a copy of a list



På Tue, 29 Apr 2008 21:30:18 +0200, skrev Trastabuga <lispercat@xxxxxxxxx>:

when copy-list or copy-tree are not deep enough?
I have a big list and I need a function that returns one of its
branches depending on condition.
Later on, in another function I use that branch and modify it
(appending other lists to it).
Now, even though I return that branch using copy-tree, still when I
modify that branch, it modifies the original tree.
Is it because copy-tree only copies conses but not the atoms
themselves?

Yes.

How can I do a deep copy of the list so it creates a completely new
instance of that branch?

Thank you,
Andrew

You write your own. copy-seq works like copy-list but works on arrays as well.
sequencep sais whether it is a sequence. Since a list is also a sequence you just need a
depth first traversal to duplicate the structure.

Something like:

(defun deep-copy-sequence (sequence)
"Recursivly copy all array's and list's."
(when (subtypep (type-of sequence) 'sequence)
(setf sequence (copy-seq sequence))
(loop for i from 0 below (length sequence) do
(setf (elt sequence i) (deep-copy-sequence (elt sequence i)))))
sequence)

TEST 52 > (defparameter a '(1 2 #(3 4 5 (1 2 3))))
A

TEST 53 > (defparameter b (deep-copy-sequence a))
B

TEST 54 > (setf (second (aref (third b) 3)) #\*)
#\*

TEST 55 > a
(1 2 #(3 4 5 (1 2 3)))

TEST 56 > b
(1 2 #(3 4 5 (1 #\* 3)))

--------------
John Thingstad
.



Relevant Pages

  • TOC of Python Cookbook now online (was Re: author index for Python Cookbook 2?)
    ... Processing a String One Character at a Time ... Finding a File on the Python Search Path ... Constructing Lists with List Comprehensions ... Looping over Items and Their Indices in a Sequence ...
    (comp.lang.python)
  • RE: modifying mutable list elements in a for loop
    ... >The python tutorial tells me "It is not safe to modify the sequence ... >mutable, such as lists or objects, e.g. ...
    (comp.lang.python)
  • Re: Subclassing list the right way?
    ... about how overriding methods on them will affect other method calls. ... special interpretation of negative indexes (if the class wishes to ... outside the set of indexes for the sequence (after any special ... either write a lot of code or restrict the way you use lists to a ...
    (comp.lang.python)
  • Re: Newbie-Question concerning list and inheritance
    ... > OK, I'm hopefully a little less of a Lisp newbie these days, but Lisp's ... lists are simply built from cons cells. ... > list, sequence, t" ... > either, really, but I can kind of see why one might want to subclass ...
    (comp.lang.lisp)
  • Re: tuple.index()
    ... You can put any combination of things into both tuples and lists. ... tuple rather than a mutable sequence like a list. ... element is no real substitute for knowing its position. ... presence of an element is as good as knowing its position (since the ...
    (comp.lang.python)