I’m trying to create an instance of a data type for a directionless edge.
Edge 1 2 == Edge 2 1 (i.e. Edge from 1 to 2 is the same as Edge from 2 to 1, direction doesn’t matter).
Here’s an example of of the data type, and Eq instance and an attempt at an Ord instance:
data Edge = Edge Int Int deriving Show
instance Eq Edge where
(Edge x1 y1) == (Edge x2 y2) = ((x1 == x2 && y1 == y2) || (x1 == y2 && y1 == x2))
instance Ord Edge where
compare e1@(Edge x1 y1) e2@(Edge x2 y2) = if e1 == e2
then EQ
else ????
Any idea how to get a totally ordered Ord instance in this case?
My answer is similar to Thomas’s, except I recommend that you normalize when you construct the edge.
Now you know that the vertex with the smaller index appears first, and the
deriving (Eq, Ord)instances will do exactly what you want. You just have to make sure you only create edges with themkEdge“smart constructor” (you can do this by puttingEdgein a module and not exporting theEdgeconstructor).