Re: How to make a copy of a list



På Tue, 29 Apr 2008 23:24:00 +0200, skrev John Thingstad <jpthing@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
.



Relevant Pages

  • Re: How to make a copy of a list
    ... (setf sequence (copy-seq sequence)) ... (loop for i from 0 below (length sequence) ... do (setf element (deep-copy-sequence element)))) ...
    (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: 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)
  • 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)