I was trying to clone an object in Scheme, something like

(define o1
    (new cl%
        [a 1] [b 2]))

and then

(define o2 o1)

When I used set! on o1, it changed o2 along with o1. But I want independent cloning with same attributes. What should I do?

有帮助吗?

解决方案

Write a copy method. Then:

(define o2 (copy-cl%-thingy o1))

Like this:

(define (new aval bval)
  `(cl% [a ,aval] [b ,bval]))
(define cl%-aval caddr)
(define cl%-bval cadddr)

(define (copy-cl%-thingy o)
  (new (cl%-aval o) (cl%-bval o)))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top