[racket] Implementing an equal? method for a class

From: Gregory Woodhouse (gregwoodhouse at me.com)
Date: Sat Jul 28 22:35:47 EDT 2012

Okay, this is really a newbie question, but here goes. I have a class that represents a Sudoku grid. Internally, the grid is stored as a vector of vectors of integers:

(define simple-grid%
  (class object%
    ;b is an internal representation of the grid and is initialized to an empty grid
    (define b(make-vector 9 (make-vector 9 0)))
    (define/public (get-cell r c)
          ([row (vector-ref b (sub1 r))])
        (vector-ref row (sub1 c))))


I provide methods get-cell to retrieve the contents of a single cell, set-cell! to (destructively) update the contents of a cell and so forth. In principle, I could implement equal? by looping all 81 cells and comparing them one by one, but this seems awkward. It seems like I ought to be able to just check that the state vectors are equal? but I have no access to b outside the class. In Java, I'd add a protected method getStateVector that could be called from within a separate method named equalTo that tells me if a grid object g1 is equivalent to a g2. Or at least I could do this. I really don't want to expose how the internal representation of the grid to other classes. Then again, maybe that's Java thinking in the context of Racket.

Posted on the users mailing list.