Skip to main content

copy-seq

copy-seq Function

Syntax:

copy-seq sequence → copied-sequence

Arguments and Values:

sequence—a proper sequence.

copied-sequence—a proper sequence.

Description:

Creates a copy of sequence. The elements of the new sequence are the same as the corresponding elements of the given sequence.

If sequence is a vector , the result is a fresh simple array of rank one that has the same actual array element type as sequence. If sequence is a list, the result is a fresh list.

Examples:

(setq str "a string")"a string" 
(equalp str (copy-seq str)) → true
(eql str (copy-seq str)) → false

Exceptional Situations:

Should be prepared to signal an error of type type-error if sequence is not a proper sequence.

See Also:

copy-list

Notes:

From a functional standpoint, (copy-seq x) (subseq x 0)

However, the programmer intent is typically very different in these two cases.

Expanded Reference: copy-seq

Creating an independent copy

copy-seq creates a new sequence with the same elements as the original. Modifications to the copy do not affect the original.

(let* ((original '(1 2 3))
(copy (copy-seq original)))
(setf (first copy) 99)
(values original copy))
=> (1 2 3)
=> (99 2 3)

Copying strings

Strings in Common Lisp are often literal and thus not modifiable. copy-seq produces a fresh, modifiable copy.

(let ((str (copy-seq "hello")))
(setf (char str 0) #\H)
str)
=> "Hello"

The copy is equalp but not eql

The copy has equal content but is a distinct object.

(let* ((s "test")
(c (copy-seq s)))
(values (equalp s c) (eql s c)))
=> T
=> NIL

Copying vectors

When given a vector, copy-seq returns a fresh simple array of the same element type.

(copy-seq #(a b c))
=> #(A B C)
(copy-seq #())
=> #()

Practical use: safe destructive operations

copy-seq is commonly used before destructive operations like sort or nreverse to preserve the original sequence.

(let ((data '(3 1 4 1 5 9)))
(sort (copy-seq data) #'<))
=> (1 1 3 4 5 9)