Ord instance for Data.Map?

Johannes Waldmann waldmann at imn.htwk-leipzig.de
Wed Apr 18 15:27:20 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. 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, 

So basically you want local instances,

    let m :: Data.Set.Set Foo
        m = Data.Set.fromList [ .... ]
             where instance Ord Foo where ....

Inability to do so is the "fundamental problem"
with type classes (+ instances):
they inhabit (pollute) a global space.

If you write a library using type classes (interfaces),
(as they told you in elementary school),
then you force the user contribute to this pollution :-)

The above (local  instance) could be modelled
by handing the required Ord dictionary explicitely
(or as an implicit parameter, which I would not recommend, though)

You can hand over the Ord dictionary when constructing a Set in Java:

> TreeSet(Comparator<? super E> comparator)
> Constructs a new, empty tree set,
> sorted according to the specified comparator.

So the Haskell collections could need a similar constructor?
The difference to your work-around (Wrapper class for the elements
of the collection) is that the constructor is called only once,
but your wrapper clutters each and every access.

(unrelated rant:) look at the above example code.
Using qualified names is generally the right thing (TM) to do,
but I still think that resulting type names as Data.Set.Set
look distinctively ugly, almost like a typo.
I would really love some shortcut (allowing to write "Data.Set" )
if a module export just one type.

Best regards, J. W.

More information about the Libraries mailing list