I'm using the -XExistentialQuantification
GHC extension to create a heterogeneous container for values of a specific type class (Shape
):
-- Container type
data Object = forall a. Shape a => Object a
-- 'Shape' class. Methods not important
class Eq s => Shape s where
doStuff :: s -> s
Given that all instances of Shape
are also instances of Eq
, is there a way to make Object
an instance of Eq
as well?
It's possible if you add a Typeable
constraint:
import Data.Typeable
data Object = forall a. (Shape a, Typeable a) => Object a
instance Eq Object where
Object x == Object y =
case cast y of
Just y' -> x == y'
Nothing -> False
Here, cast y
will return Just y'
if the desired type of y'
(inferred from the use of ==
with x
) matches the actual type of y
, and Nothing
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With