1
votes

I have a container type, called X. Since I want heterogeneous lists over X, its constructor is existentially typed over some type variable a. However, I want it to be an instance of the Eq type class. A hackish solution looks like this:

{-# LANGUAGE GADTs #-}

data X where X :: (Eq a, Show a) => a -> X

instance Eq X where
    X x == X y = show x == show y

What would be the simplest (clean) solution for this problem?

(Xs don't equal if they don't have the same type.)

1

1 Answers

7
votes

Add Typeable so that you have a runtime representation of the type; then use cast to cast one of them to the appropriate type.

{-# LANGUAGE GADTs #-}
import Data.Typeable

data X where X :: (Eq a, Typeable a) => a -> X

instance Eq X where 
    X x == X y = Just x == cast y