From: Gisle Sælensminde
Subject: Copy a clos class instance
Date: 
Message-ID: <slrnd2tnob.6c3.gisle@kaktus.ii.uib.no>
When working with structures, defstruct automatically defines a copy function
e.g:

(defstruct mystruct 
 (a 1)
 (b 0))

(defparameter *the-struct* (make-mystruct))

(copy-mystruct *the-struct*)

When working with CLOS classes, I have not found a way to copy a class
instance in an easy way without implementing a copy method for each 
class. Is there a way doing this. 

-- 
Gisle S�lensminde, Phd student, Scientific programmer
Computational biology unit, University of Bergen, Norway
Email: ·····@cbu.uib.no | Complicated is easy, simple is hard.

From: ····@hotpop.com
Subject: Re: Copy a clos class instance
Date: 
Message-ID: <1110376404.352873.130990@z14g2000cwz.googlegroups.com>
This is a bit more general, but (make-instance-from-object obj
(class-of obj)) is almost what you want except for needing initargs for
the slots to be copied.

(defun make-instance-from-object (obj class &rest extra-initargs)
  "Create an instance of CLASS and pass initargs for slots common with
OBJ."
  (unless (typep class 'class)
    (setq class (find-class class)))
  (let ((args ()))
    (dolist (slot (class-slots class))
      (let ((slot-name (slot-definition-name slot)))
        (when (and (slot-exists-p obj slot-name)
                   (slot-boundp obj slot-name))
          (if-bind (initarg (first (slot-definition-initargs slot)))
                   (setq args (cons initarg
                                    (cons (slot-value obj slot-name)
                                          args)))
                   (warn "No initarg for ~S" (slot-definition-name
slot))))))
    (apply #'make-instance class (append extra-initargs args))))

G�r
From: Pascal
Subject: Re: Copy a clos class instance
Date: 
Message-ID: <3986voF5vruaaU1@individual.net>
Gisle S�lensminde wrote:
> When working with structures, defstruct automatically defines a copy function
> e.g:
> 
> (defstruct mystruct 
>  (a 1)
>  (b 0))
> 
> (defparameter *the-struct* (make-mystruct))
> 
> (copy-mystruct *the-struct*)
> 
> When working with CLOS classes, I have not found a way to copy a class
> instance in an easy way without implementing a copy method for each 
> class. Is there a way doing this. 

No, because there's no general approach for copying objects that works 
in all cases.

If you want to implement a naive general-purpose copy operator on your 
own, you can iterate over (class-slots (class-of (object)) and do what's 
necessary (given that your CL implementation provides at least the 
introspective part of the CLOS MOP).


Pascal