Reputation: 3942
For example, I have two structure instances s1
and s2
, but I don't know the exact type of s1
and s2
. Is it possible to check whether s1
and s2
are of the same structure type or not?
Upvotes: 2
Views: 2648
Reputation: 60084
(the original question was not restricted to racket)
Use type-of
:
(eq (type-of s1) (type-of s2))
You can also use class-of
instead; it does not matter for structures but does matter for other types; you need to think carefully about what you are trying to do. type-of
is more granular, but may not return an atom
, so you might not be able to use eq
with it.
EDIT: it appears that racket has class-of
too, so you can use that.
Upvotes: 0
Reputation: 8533
It is not in general possible to check that property, namely because structs in Racket are often opaque, meaning that reflective operations give you limited or no information about the struct instance.
If the structure types are declared as transparent, however, it is possible to determine if they originated from the same structure type using struct-info
.
#lang racket
(struct s () #:transparent)
(struct t () #:transparent)
(define-values (s-info _) (struct-info (s)))
(define-values (t-info _) (struct-info (t)))
(equal? s-info t-info) ; => #f
(define-values (s-info-2 _) (struct-info (s)))
(equal? s-info s-info-2) ; => #t
If you just want an approximation of this information, you can follow Greg's advice and use object-name
. Note that it is possible for two structure types that do not produce equivalent instances to have the same object name:
(define s1 (let () (struct s ()) (s)))
(define s2 (let () (struct s ()) (s)))
(equal? (object-name s1) (object-name s2)) ; => #t
Upvotes: 4
Reputation: 16260
Racket -- #lang racket
, the main/full language -- does not have a type-of
or class-of
.
Instead you could use object-name
for this:
#lang racket
(struct s ())
(struct t ())
(define x (s))
(define y (s))
(define z (t))
(object-name x) ; 's
(object-name y) ; 's
(object-name z) ; 't
(equal? (object-name x) (object-name y)) ; #t
(equal? (object-name x) (object-name z)) ; #f
Upvotes: 4