Difficulty: Easy
Correct Answer: returns a new list that is equal to by copying the top-level elements of
Explanation:
Introduction / Context:
In Common Lisp, lists are typically built from cons cells. When you copy a list, it is vital to understand whether the copy is shallow (top-level cons cells duplicated, elements shared) or deep (recursively duplicated). The standard function copy-list
performs a shallow copy of a list’s top-level structure.
Given Data / Assumptions:
copy-list
.<list>
.
Concept / Approach:
copy-list
constructs a new chain of cons cells replicating the top-level structure of the input list while reusing (sharing) the element objects themselves. If the elements are atoms (numbers, symbols) or if they are lists, the inner lists are not duplicated—only their references are copied. Therefore, modifications to the new list’s top-level cons cells do not affect the original’s structure, but mutations to shared sublists or objects will be visible from both lists.
Step-by-Step Solution:
(copy-list L)
on list L
.Implementation allocates new cons cells for each top-level pair in L
.It sets each new cons cell’s car
to the original element reference and cdr
to the next new cons cell.Result is a new list equal (equalp as appropriate) to L
at top level.
Verification / Alternative check:
A common demonstration: let L = (list (list 1 2) 3)
. After (setf L2 (copy-list L))
, altering (cdr L2)
does not change L
structure, but modifying the inner sublist (setf (caar L2) 9)
affects both, because the sublist is shared.
Why Other Options Are Wrong:
length
, not copy-list
.null
, not copying.
Common Pitfalls:
Confusing shallow vs. deep copy; expecting copy-list
to duplicate nested lists recursively (use copy-tree
for that).
Final Answer:
returns a new list that is equal to <list> by copying the top-level elements of <list>
Discussion & Comments