Overriding equals, hashCode and toString in a Clojure deftype

Posted by mikera on Stack Overflow See other posts from Stack Overflow or by mikera
Published on 2010-06-10T20:46:13Z Indexed on 2010/06/10 22:02 UTC
Read the original article Hit count: 364

Filed under:
|
|
|

I'm trying to create a new type in Clojure using deftype to implement a two dimensional (x,y) coordinate, which implements a "Location" protocol.

I'd also like to have this implement the standard Java equals, hashCode and toString methods.

My initial attempt is:

 (defprotocol Location   
   (get-x [p])  
   (get-y [p])   
   (add [p q]))


 (deftype Point [#^Integer x #^Integer y]   
     Location
       (get-x [p] x)
       (get-y [p] y) 
       (add [p q] 
         (let [x2 (get-x q)
               y2 (get-y q)]
           (Point. (+ x x2) (+ y y2))))   
     Object
       (toString [self] (str "(" x "," y ")"))
       (hashCode [self] (unchecked-add x (Integer/rotateRight y 16)))
       (equals [self b] 
         (and 
           (XXXinstanceofXXX Location b) 
           (= x (get-x b)) 
           (= y (get-y b)))))

However the equals method still needs some way of working out if the b parameter implements the Location protocol.

What is the right approach? Am I on the right track?

© Stack Overflow or respective owner

Related posts about clojure

Related posts about equals