[plt-scheme] Cloning objects?

From: Laurent (laurent.orseau at gmail.com)
Date: Tue Dec 8 11:32:27 EST 2009

Hi all,

This has probably been asked a few times before, but I couldn't find
anything relevant.
What is the best way to create a generic system to clone an object? (am I
missing something obvious?)

You can still of course create a `copy' method that must be overridden, but
this can be risky if the class gets extended and some initializations may be
forgotten, or when creating a new child class and forgetting to override the

So I tried to use (inspect #f) and using `struct-copy', which worked, but
that is awful.

Another way is to use a modified `init-field' form which can take a source
object of the same class and initializes the fields with the values of the
object or with a default value. Just a quick first try:

(define-syntax-rule (init-field-clone source [var val] ...)
>   (begin
>     (init [source #f])
>     (init-field [var (if source (get-field var source) val)] ...)))

 ; Tests:
> (define c1%
>     (class object%
>       (init-field-clone source [x 1] [y 2])
>       (super-new)
>       (define/public (vals)(list x y))
>       ))
> > (define o1 (new c1% [x "x"] [y "y"]))
> > (send o1 vals)
> ("x" "y")
> > (define o2 (new c1% [source o1]))
> > (send o2 vals)
> ("x" "y")

So that simple form works too but it limits the class model (and I guess it
would be a bit cumbersome to take it all into account).
And, BTW, despite the use of `define-syntax-rule', when omitting the
`source' argument in the `init-field-clone' definition,
the form still works but becomes non-hygienic! Now I have to completely
rewire my brain again...

Probably another way could be to serialize/deserialize, but I don't think
that is the purpose of serialization...

My question is thus: do the Scheme gurus know the best generic way to make
an object cloning system?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20091208/3d601982/attachment.html>

Posted on the users mailing list.