Search code examples
lispcommon-lispstructureshallow-copy

how to create deep copies of structures


How do I copy a structure in Common Lisp? I created a structure like:

(defstruct state board player previous-move depth)

Board is a 2 dimension array. I tried doing:

(setf new-state state)

When I change something in new-state, the changes in the 2 dimension array also occur in state. How can I create a copy of a structure like state and change it independently?


Solution

  • Common Lisp gives you two ways:

    • with DEFSTRUCT state there is a function copy-state defined.

    • the function COPY-STRUCTURE copies a structure

    Note that these are shallow copies. Only the slot references get copied. There won't be a copy of the referenced data.

    To copy the array, you would need to write a routine (possibly there are library routines).