-->

我怎样才能得到GHC产生Data.Typeable的情况下,在上下文中与分型GADTs?(How c

2019-08-17 19:49发布

假设我有以下代码:

{-# LANGUAGE GADTs, DeriveDataTypeable, StandaloneDeriving #-}
import Data.Typeable

class Eq t => OnlyEq t
class (Eq t, Typeable t) => BothEqAndTypeable t

data Wrapper a where
    Wrap :: BothEqAndTypeable a => a -> Wrapper a

deriving instance Eq (Wrapper a)
deriving instance Typeable1 Wrapper

接着,下面的实例声明的作品, 不受制约t

instance OnlyEq (Wrapper t)

和做什么,我希望它做的事。


但是,下面的实例声明不工作:

instance BothEqAndTypeable (Wrapper t)

因为GHC - 我使用7.6.1 - 抱怨说:

No instance for (Typeable t)
  arising from the superclasses of an instance declaration
Possible fix:
  add (Typeable t) to the context of the instance declaration
In the instance declaration for `BothEqAndTypeable (Wrapper t)'

添加Typeable t的背景下工作,当然。 但这样做增加了以下实例:

instance Typeable (Wrapper t) where
    typeOf (Wrap x) = typeOf1 (Wrap x) `mkAppTy` typeOf x

有没有办法让GHC写这后一种情况下我吗? 如果是这样,怎么样? 如果不是,为什么不呢?

我希望GHC将能够拉Typeable从上上下文约束Wrap构造,只是因为它与没有Eq约束。 我认为我的问题归结为一个事实,即GHC明确禁止写deriving instance Typeable (Wrapper t)标准(Typeable1 s, Typeable a) => Typeable (sa)实例不能“往里” sa找一Typeable a字典。

Answer 1:

我希望GHC将能够拉Typeable从上上下文约束Wrap构造

如果它有一个Wrap构造,它可以拉Typeable从它的约束。

不过,这并不有一个Wrap构造。

所不同的是, Eq实例使用的价值,所以它无论是Wrap something ,其中Wrap构造使得Eq字典包装类型可用,一切都很好,或者它的 ,然后一切都很好过,评估x == y到底。

需要注意的是派生

instance Eq (Wrapper a)

没有一个Eq对类型变量约束a

Prelude DerivT> (undefined :: Wrapper (Int -> Int)) == undefined
*** Exception: Prelude.undefined
Prelude DerivT> (undefined :: (Int -> Int)) == undefined

<interactive>:3:29:
    No instance for (Eq (Int -> Int)) arising from a use of `=='
    Possible fix: add an instance declaration for (Eq (Int -> Int))
    In the expression: (undefined :: Int -> Int) == undefined
    In an equation for `it':
        it = (undefined :: Int -> Int) == undefined

Typeable情况下不得利用价值的,所以没有见底,如果提供的值不是一个Wrap something

因此,衍生的instance Typeable1 Wrapper用品

instance Typeable t => Typeable (Wrapper t)

但不是无约束的

instance Typeable (Wrapper t)

而不受约束的情况下不能用GHC来的。

因此,你必须要么提供一个约束

instance Typeable t => BothEqAndTypeable (Wrapper t)

或无约束

instance Typeable (Wrapper t)

你自己。



文章来源: How can I get GHC to generate instances of Data.Typeable for GADTs with Typeable in the context?