Comparing objects in Racket
Equality methods
By implementing a method for equality equal-to? and two extraction methods equal-hash-code-of and equal-secondary-hash-code-of we can define our own object comparison rules.
For more info see Object Equality and Hashing.
Consider the following example:
(define integer%
(class* object% (equal<%>)
(super-new)
(init-field [value 0])
(define/public (equal-to? other-object recur)
(= value (get-field value other-object)))
(define/public (equal-hash-code-of hash-code)
(hash-code value))
(define/public (equal-secondary-hash-code-of hash-code)
(hash-code value))))If we create a new integer% object we can notice that it is not transparent (we can not inspect values of any of it’s fields).
(new integer%)
;; => (object:integer% ...)But if we compare two fresh integer% objects they will be equal.
(equal? (new integer%) (new integer%))
;; => #trueTransparent class
A transparent cvlass is a class with the inspect expression valuye se to #false.
From Racket documentation Creating Classes:
Just as for structure types, an inspector controls access to the class’s fields, including private fields, and also affects comparisons using equal?.
Consider the following example:
(define integer%
(class object%
(super-new)
(inspect #false)
(init-field [value 0])))If we create a new integer% object we can see it’s field values.
(new integer%)
;; => (object:integer% 0)And if we compare two fresh integer% objects they will be equal.
(equal? (new integer%) (new integer%))
;; => #true