[racket] equal? and objects

From: Danny Yoo (dyoo at cs.wpi.edu)
Date: Wed Dec 22 15:20:44 EST 2010

> I am trying to implement an is-equal? function like this:
>
>    ;; is-equal? : the-obj -> boolean
>    (define/public (is-equal? another-obj)
>      (andmap (λ (field-name)
>                 (equal? (get-field field-name another-obj)
>                         field-name))
>              (field-names this)))
>
> Could anyone help me as to why this does not work, or an alternative
> approach?


Alternative approach: you can allow equal? to work on instances by
using (inspect #f) in the class definition.  For example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket

(define person%
   (class object%
     (inspect #f)  ;; this allows equal? to work on person% instances
     (super-new)
     (init-field name)))

(define p1 (new person% [name "george"]))
(define p2 (new person% [name "danny"]))
(define p3 (new person% [name "george"]))

(equal? p1 p2)
(equal? p1 p3)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

When we set the inspector to #f, we allow things like equal? to dive
into the fields of the instances.
http://docs.racket-lang.org/reference/objectequality.html has more
details on customizing equal? on instances.


Posted on the users mailing list.