GHC.Generics示例不起作用

时间:2015-03-02 04:21:14

标签: haskell generics

我试图让GHC.Generics中描述的通用二进制编码类的示例实现起作用,但是当我尝试编译它时,我得到一个错误。

import GHC.Generics

class Encode' f where
  encode' :: f p -> [Bool]

instance Encode' V1 where
  encode' x = undefined

instance Encode' U1 where
  encode' U1 = []

instance (Encode' f, Encode' g) => Encode' (f :+: g) where
  encode' (L1 x) = False : encode' x
  encode' (R1 x) = True  : encode' x

instance (Encode' f, Encode' g) => Encode' (f :*: g) where
  encode' (x :*: y) = encode' x ++ encode' y

instance (Encode c) => Encode' (K1 i c) where
  encode' (K1 x) = encode x

instance (Encode' f) => Encode' (M1 i t f) where
  encode' (M1 x) = encode' x

class Encode a where
  encode :: a -> [Bool]
  default encode :: (Generic a) => a -> [Bool]
  encode x = encode' (from x)

GHC抱怨:

Could not deduce (Encode' (Rep a)) arising from a use of ‘encode'’
from the context (Encode a)
  bound by the class declaration for ‘Encode’
  ...
or from (Generic a)
  bound by the type signature for encode :: Generic a => a -> [Bool]
  ...
In the expression: encode' (from x)
In an equation for ‘encode’: encode x = encode' (from x)

我错过了什么?

1 个答案:

答案 0 :(得分:5)

并非Generic的所有内容都可以由encode'进行编码。只有同时具有Generic实例的Rep a且具有代表性Encode'的内容才能由通用encode'进行编码。编译器不知道(并且不能知道)Generic不被Rep实例覆盖的Encode'内容GenericRep实例的作者可以使用尚未存在的Encode' (Rep a)类型。

您需要将所请求的default encode约束添加到default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool] 的上下文中。

{{1}}
相关问题