Ord instance for Data.Map?

Henning Thielemann lemming at henning-thielemann.de
Mon Apr 16 10:47:22 EDT 2007

I wonder whether the Ord instance is a good choice as constraint for
Data.Map, Data.Set and so on. I want to manage complex numbers and residue
classes in a set, or polynomials as keys of maps, but I hesitate to make
them instances of Ord, because "a<b" shall remain a type error for complex
numbers, residue classes and polynomials. Also in Haskore we abuse Ord
instance to get canonical form of arranged notes. However there is no
notion of magnitude for notes, so the Ord instance is rather artificial.

I have a work-around in mind: I could introduce

class Eq a => Indexable a where
  compareIndex :: a -> a -> Ordering

then make several mathematical object types instances of this class. Then
make a wrapper type

newtype IndexableToOrd a = Cons a

which maps the Indexable instance to an Ord instance:

instance Indexable a => Ord (IndexableToOrd a) where
   compareIndex (Cons x) (Cons y) = compare x y

Then I do not insert complex numbers immediately in a set, but wrap them
in IndexableToOrd and insert the wrapped values in a set.
 Cumbersome, isn't it? So my question is: Was the Ord constraint for
Data.Map a good idea? If yes, are there simpler work-arounds than mine?
I think, that '<' and '>' imply something like comparisons of magnitudes
and the Data.Map doesn't require that notion and it is happy with any
total ordering.

Btw. is there a Data.Map.unzip?

More information about the Libraries mailing list