Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Util suggestion: copy-object #100

Open
Ambrevar opened this issue Dec 8, 2021 · 1 comment
Open

Util suggestion: copy-object #100

Ambrevar opened this issue Dec 8, 2021 · 1 comment

Comments

@Ambrevar
Copy link

Ambrevar commented Dec 8, 2021

I might be missing an existing implementation of copy-object, but I find it useful sometimes.

Shallow copy:

(defmethod copy-object (object &rest slot-overrides)
  (let ((class-sym (class-name (class-of object))))
    (apply #'make-instance class-sym
           (append
            slot-overrides
            (alexandria:mappend
             (lambda (slot)
               (list (intern (symbol-name slot) "KEYWORD")
                     (slot-value object slot)))
             (mopu:slot-names class-sym)))))) 
  • I suggest making it a method so that users can specialize the copy on their own specific objects.
  • Indeed, the above function assumes that the initarg is the keyword version of the slot name. This is a strong assumption that won't work in all cases.
  • The above function copies the slots in the make-instance call so that initialize-instance :after has the slots set the right values already. Without this requirement, we could first call make-instance without initializing any slot and then loop over the slots, which has the benefit of not relying on a guess of the initargs. The downside is that some classes require slot values at make-instance time.
  • Maybe add an argument to allow for deep copies, that is, replace slot-value with copy-object so that it copies the slots recursively.

Thoughts?

@ruricolist
Copy link
Owner

ruricolist commented Jan 2, 2022

I'll think about this. I don't want to take on the bigger issue of what it means to "copy" something (see Pitman's essay on the subject), but I could see a place for a shallow copy-object function that works for CLOS objects the same way copy-structure works for structs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants