Question

Is it possible to implement a type class as follows:

class SomeClass e where
    isEq :: (SomeClass e') => e -> e' -> Bool

where isEq x y would return true when x and y are both the same instance of this type class?

Context: This is a thinly-veiled attempt at getting run-time type tests. While at first I read that Haskell has type erasure, I've also read that with recent extensions to GHC, some run-time information in there.

edit: for those wondering about my usecase... I've been using type-level programming to ensure certain properties of some of my ADTs, namely involving resource usage. These resources are represented by distinct types (and resource locks are accordingly implemented at type level).

I'm attempting to write an optimisation procedure that requires identification of resource writing/reading. But since all my resources are represented by distinct singletons, whose only common factor (apart from all values being bottom) is the typeclass which groupes them together.

In a nutshell I want to use the results of my type-level programming at a run-time, value level.

Was it helpful?

Solution

You can do this, as hinted at by Karolis Juodelė, with Data.Typeable:

Prelude Data.Typeable> :{
Prelude Data.Typeable| let isEq :: (Typeable a , Typeable b) => a -> b -> Bool
Prelude Data.Typeable|     isEq x y = typeOf x == typeOf y
Prelude Data.Typeable| :}
Prelude Data.Typeable> isEq True ()
False
Prelude Data.Typeable> isEq True False
True

The question is: Why would you not know at run time what the types are, and then why would you care about whether they are equal – can you elaborate your use case?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top