7

假设我有以下代码:

{-# 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 (s a)实例无法“查看内部”s a来查找Typeable a字典。

4

1 回答 1

5
于 2013-03-20T18:50:54.613 回答