Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived instance in Haskell

I would like to use derived instance like this:

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)

But I received from 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’

This way is very convenient for my project. I can not find the solution.

Is any way of using derived instance for such data?

like image 694
QSpider Avatar asked Sep 04 '17 06:09

QSpider


People also ask

What is deriving in Haskell?

The definition of deriving on stack overflow is: "In Haskell, a derived instance is an instance declaration that is generated automatically in conjunction with a data or newtype declaration. The body of a derived instance declaration is derived syntactically from the definition of the associated type."

What is an instance Haskell?

An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.


1 Answers

Is any way of using derived instance for such data?

Yes. Do what GHC suggested, make a standalone deriving clause:

{-# LANGUAGE StandaloneDeriving, ExistentialQuantification #-}

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

deriving instance Show Test3D

What you cannot do is derive an Eq instance, because different values may actually contain different types and it's only possible to compare these with a dynamic-cast hack through Typeable.

like image 66
leftaroundabout Avatar answered Sep 29 '22 03:09

leftaroundabout