Anonymous user
Polymorphic copy: Difference between revisions
→{{header|Racket}}: Add method to copy transparent structures
m (Racket →Using classes: use inherit-field) |
(→{{header|Racket}}: Add method to copy transparent structures) |
||
Line 1,299:
=={{header|Racket}}==
===Using
This method is useful only for prefab structures.
Only prefab-structures can be copied on the fly. It’s possible to copy other structure using generics or structure-type-properties to implement a “magic” method.▼
<lang Racket>#lang racket/base
Line 1,317:
(let* ([original (point/color 0 0 'black)]
[copied (copy-prefab-struct original)])
(displayln copied)
(displayln (eq? original copied)))</lang>
{{out}}
<pre>#s(struct:point 0 0)
#f
#s(struct:point/color 0 0 black)
#f
</pre>
===Using transparent structures===
This method can be applied to prefab or transparent structures, or using a powerful enough inspector. The example uses transparent structures.
▲
<lang Racket>#lang racket/base
(define (copy-struct str)
(define-values (str-struct-info _) (struct-info str))
(define str-maker (struct-type-make-constructor str-struct-info))
(apply str-maker (cdr (vector->list (struct->vector str)))))
(struct point (x y) #:transparent)
(struct point/color point (color) #:transparent)
(let* ([original (point 0 0)]
[copied (copy-struct original)])
(displayln copied)
(displayln (eq? original copied)))
(let* ([original (point/color 0 0 'black)]
[copied (copy-struct original)])
(displayln copied)
(displayln (eq? original copied)))</lang>
|