简体   繁体   English

GADT,未参数化的类型以及它们的实例Eq

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM