[英]GADTs, unparametrized types and instance Eq for them
I have a container type, called X
. 我有一个名为X
的容器类型。 Since I want heterogeneous lists over X
, its constructor is existentially typed over some type variable a
. 由于我想要X
异类列表,因此它的构造函数在某些类型变量a
存在地类型化。 However, I want it to be an instance of the Eq
type class. 但是,我希望它是Eq
类型类的实例。 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? 解决此问题最简单(干净)的方法是什么?
( X
s don't equal if they don't have the same type.) (如果X
的类型不同,则X
并不相等。)
Add Typeable
so that you have a runtime representation of the type; 添加Typeable
以便您拥有该类型的运行时表示形式; then use cast
to cast one of them to the appropriate type. 然后使用cast
转换将其中之一转换为适当的类型。
{-# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.