Ord instance for Data.Map?
bertram.felgenhauer at googlemail.com
Tue Apr 17 00:21:52 EDT 2007
Henning Thielemann wrote:
> I wonder whether the Ord instance is a good choice as constraint for
> Data.Map, Data.Set and so on.
In the case where there are Ord instances they are a good choice. Adding
another type class for this purpose has the disadvantage that you have
to write class instances for them, for all existing types that have Ord
instances; while trivial this still adds up to quite a few lines of
boilerplate code. This has to be weighted against the added boilerplate
code for cases where a total order can be defined but is rather
artificial. Right now I think that this is the exception rather than the
rule. Changing the library interface should also not be done lightly.
[snip examples: Complex numbers and Haskore notes]
> I have a work-around in mind: I could introduce
> class Eq a => Indexable a where
> compareIndex :: a -> a -> Ordering
Personally I'd do it without an Indexable class; just
> newtype Index a = Index a
> instance Ord x => Ord (Index (Complex x)) where
> (Index (Complex a b)) `compare` (Index (Complex c d)) =
> (a, b) `compare` (c, d)
should be good enough. 'Index' marks the purpose for the type.
Note that for me, Ord alone really only implies a total order. If a
type has both Num and Ord instances that is different; I understand
your concerns about providing an Ord instance for Complex numbers
> 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?
Of course you still need that index wrapping. If this gets out of hand
it can be put into a simple wrapper around Data.Map though, without
changing any existing libraries.
> So my question is: Was the Ord constraint for Data.Map a good idea?
I still think it was.
More information about the Libraries