Haskell 中的派生实例

Derived instance in Haskell

我想像这样使用派生实例:

data Test3D = forall a. (Show a, Eq a, Typeable a, Generic a)
                => Test3D { testDt :: String
                          , testPrm :: a
                          }
   deriving (Show, Eq, Typeable, Generic)

instance Binary (Test3D)
$(deriveJSON defaultOptions ''Test3D)

但是我从 GHC 收到了:

• Can't make a derived instance of ‘Show Test3D’:
        Constructor ‘Test3D’ has existentials or constraints in its type
        Possible fix: use a standalone deriving declaration instead
• In the data declaration for ‘Test3D’

这种方式对我的项目来说很方便。我找不到解决方案。

是否有任何方法可以为此类数据使用派生实例?

Is any way of using derived instance for such data?

是的。按照 GHC 的建议进行操作,创建一个 standalone 派生子句:

{-# LANGUAGE StandaloneDeriving, ExistentialQuantification #-}

data Test3D = forall a. (Show a)
                => Test3D { testDt :: String
                          , testPrm :: a
                          }

deriving instance Show Test3D

你不能做的是派生一个 Eq 实例,因为不同的值实际上可能包含不同的类型,并且只能通过 Typeable.[=14 将它们与动态转换 hack 进行比较=]