In Common Lisp, what does the function (copy-list <list>) return?

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:

  • The function under discussion is copy-list.
  • Argument is a proper list <list>.
  • We need to know exactly what the returned value represents.


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:

Call (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:

  • Returns the length: that is length, not copy-list.
  • Returns T if empty: that is essentially testing with null, not copying.
  • All of the above: cannot be true because the other statements are false.
  • None of the above: incorrect because the first statement is correct.


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>

More Questions from Artificial Intelligence

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion