[Haskell-cafe] Data.Typeable TypeRep Ord instance.

Andreas Baldeau andreas at baldeau.net
Thu Dec 30 08:35:57 CET 2010


On 01:08 Sun 05 Dec     , Serguey Zefirov wrote:
> Why TypeRep does have equality and doesn't have ordering?
> 
> It would be good to have that.

I think the problem is, that it's hard to give an ordering that stays the
same for all runs of your program. If you don't need this property you could
use typeRepKey to give an instance as follows:

instance Ord TypeRep where
    compare t1 t2 =
        compare
            (unsafePerformIO (typeRepKey t1))
            (unsafePerformIO (typeRepKey t2))

I know it's not good style to use unsafePerformIO, but if you look at how
typeRepKey is implemented I think it should be okay:

typeRepKey :: TypeRep -> IO Int
typeRepKey (TypeRep (Key i) _ _) = return i

(The Eq instance also uses the key for comparison.)

> Right now when I have to order two type representations I convert them
> to string and then compare. This is somewhat inefficient and not quite
> straightforward.

The implementation above should be efficient but should not be used when
data between multiple runs since the ordering may change.

Andreas



More information about the Haskell-Cafe mailing list