Polymorphic copy: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
(→{{header|TXR}}: New section.) |
||
Line 2,198: | Line 2,198: | ||
this is Abracadabra in ::oo::Obj5, stepped 2 times |
this is Abracadabra in ::oo::Obj5, stepped 2 times |
||
</pre> |
</pre> |
||
=={{header|TXR}}== |
|||
TXR Lisp has a <code>copy</code> function that produces copies of objects of all sorts. |
|||
Structures are shallowly copied; the <code>copy-struct</code> function is used when the |
|||
argument is a structure. Our polymorphic object can use <code>copy</code> to make a shallow copy of itself which shares a reference to the contained object. Then break the reference by calling <code>copy</code> on the object contained in the copy. |
|||
<syntaxhighlight lang="txrlisp">(defstruct base () |
|||
(:method identify (self) (put-line "base"))) |
|||
(defstruct derived (base) |
|||
(:method identify (self) (put-line "derived"))) |
|||
(defstruct poly () |
|||
obj |
|||
(:method deep-copy (self) |
|||
(let ((c (copy self))) ;; make copy of s |
|||
(upd c.obj copy) ;; copy self's obj |
|||
c))) ;; return c |
|||
;; Test |
|||
(let* ((b (new base)) |
|||
(d (new derived)) |
|||
(p (new poly obj d))) |
|||
b.(identify) ;; prints base |
|||
d.(identify) ;; prints derived |
|||
(let ((c p.(deep-copy))) |
|||
p.obj.(identify) ;; prints derived |
|||
(prinl (eq p.obj c.obj)))) ;; prints nil: c.obj is not a ref to p.obj</syntaxhighlight> |
|||
{{out}} |
|||
<pre>base |
|||
derived |
|||
derived |
|||
nil</pre> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |