1

我正在尝试将加密哈希存储为记录类型中的字段,但编译器抱怨:

HashTest.hs:13:1: error:
• No instance for (Data (Digest MD5))
    arising from the second field of ‘MyRecord’ (type ‘Digest MD5’)
  Possible fix:
    use a standalone 'deriving instance' declaration,
      so you can specify the instance context yourself
• When deriving the instance for (Data MyRecord)
   |
13 |                          } deriving (Show, Eq, Data, Generic)
   |                                                ^^^^

这是代码:

{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE DeriveDataTypeable    #-}

module Playpen.HashTest.HashTest where

import Data.Generics (Data, Typeable)
import GHC.Generics (Generic)

import Crypto.Hash

data MyRecord = MyRecord { idx :: Int
                         , sig :: Digest MD5
                         } deriving (Show, Eq, Generic)

如果我编写一个独立的“派生实例”子句如下......

{-# LANGUAGE DeriveGeneric         #-}
{-# LANGUAGE DeriveDataTypeable    #-}
{-# LANGUAGE StandaloneDeriving    #-}

module Playpen.HashTest.HashTest where

import Data.Generics (Data, Typeable)
import GHC.Generics (Generic)

import Crypto.Hash

data MyRecord = MyRecord { idx :: Int
                         , sig :: Digest MD5
                         } deriving (Show, Eq, Generic)

deriving instance Data MyRecord

...然后错误变为

HashTest.hs:16:1: error:
    • No instance for (Data (Digest MD5)) arising from a use of ‘k’
    • In the expression: ((z MyRecord `k` a1) `k` a2)
      In an equation for ‘Data.Data.gfoldl’:
          Data.Data.gfoldl k z (MyRecord a1 a2)
            = ((z MyRecord `k` a1) `k` a2)
      When typechecking the code for ‘Data.Data.gfoldl’
        in a derived instance for ‘Data MyRecord’:
        To see the code I am typechecking, use -ddump-deriv
      In the instance declaration for ‘Data MyRecord’
   |
16 | deriving instance Data MyRecord
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

HashTest.hs:16:1: error:
    • No instance for (Data (Digest MD5)) arising from a use of ‘k’
    • In the expression: k (k (z MyRecord))
      In an equation for ‘Data.Data.gunfold’:
          Data.Data.gunfold k z _ = k (k (z MyRecord))
      When typechecking the code for ‘Data.Data.gunfold’
        in a derived instance for ‘Data MyRecord’:
        To see the code I am typechecking, use -ddump-deriv
      In the instance declaration for ‘Data MyRecord’
   |
16 | deriving instance Data MyRecord
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

谁能帮我理解这个错误以及如何解决它?

4

2 回答 2

2

一种选择是跳过DataandGeneric实例,直到确实需要它们为止;然后在这一点上充分了解DataGeneric手动实施它们。

于 2019-04-22T15:05:55.123 回答
1

要为您的类型派生一个Data实例,它包含的所有类型也应该具有该实例。

也做Digest MD5一个实例Data

于 2019-04-21T09:03:28.733 回答