Re: How to make a copy of a list
- From: "John Thingstad" <jpthing@xxxxxxxxx>
- Date: Tue, 29 Apr 2008 22:26:55 +0200
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
.
- Follow-Ups:
- Re: How to make a copy of a list
- From: John Thingstad
- Re: How to make a copy of a list
- References:
- How to make a copy of a list
- From: Trastabuga
- How to make a copy of a list
- Prev by Date: Re: Common Lisp: Forward reference to a symbol in an unloaded package, possible?
- Next by Date: Re: array initialisation
- Previous by thread: How to make a copy of a list
- Next by thread: Re: How to make a copy of a list
- Index(es):
Relevant Pages
|