Re: How to make a copy of a list



On Apr 29, 5:54 pm, "John Thingstad" <jpth...@xxxxxxxxx> wrote:
På Tue, 29 Apr 2008 23:24:00 +0200, skrev John Thingstad
<jpth...@xxxxxxxxx>:



(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)

Third and final version.. Trades succinctness for efficiency.
Lisp needs a efficient generic iterator over a sequence..
(Looking at the macroexpansion of iter it was just length and elt under
the hood)

(defun deep-copy-sequence (sequence)
"Recursivly copy all array's and list's."
(cond
((arrayp sequence)
(setf sequence (copy-seq sequence))
(loop for element across sequence
when (subtypep (type-of element) 'sequence)
do (setf element (deep-copy-sequence element))))
((listp sequence)
(setf sequence (copy-list sequence))
(loop for element in sequence
when (subtypep (type-of element) 'sequence)
do (setf element (deep-copy-sequence element)))))
sequence)

--------------
John Thingstad

John, your original version of deep-copy-sequence works, but the
latest doesn't (the original list gets changed).
I can't put my finger on it, the simple copy-list should work, but the
tree is so complicated so I can't make a simple test and show why the
original list gets mutilated.
Thank you!

Andrew
.



Relevant Pages

  • Re: How to make a copy of a list
    ... (setf sequence (copy-seq sequence)) ... (loop for i from 0 below (length sequence) ...
    (comp.lang.lisp)
  • Re: How to make a copy of a list
    ... sequencep sais whether it is a sequence. ... (defun deep-copy-sequence (sequence) ... (setf sequence (copy-seq sequence)) ... (iter (for element in-sequence sequence) ...
    (comp.lang.lisp)
  • Re: Iterating Functions
    ... previous iterations will be lost. ... Re-Read the table "ORDER BY" the sequence number ... indicates a loop!! ... nested Recordset objects but one Connection object with success. ...
    (microsoft.public.scripting.vbscript)
  • Re: Question about loop
    ... The basic question is can loop be used to write ... Is Common Lisp one of those languages that pretends DELETE is a high ... There has been at least one conforming implementation of Common Lisp ... Sequence may be destroyed and used to construct the result; ...
    (comp.lang.lisp)
  • Re: FizzBuzz
    ... It depends how you do the loop unrolling. ... reason for needing ... On the host we can generate that sequence and look for patterns. ...
    (comp.lang.forth)