Haskell GHC.泛型示例不';行不通
我试图让中描述的通用二进制编码类的示例实现正常工作,但是当我试图编译下面的代码时,我得到了一个错误Haskell GHC.泛型示例不';行不通,haskell,generics,Haskell,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
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)
我遗漏了什么?不是所有
通用的都可以通过encode'
编码。只有那些既属于泛型
又具有表示形式的事物,repa
具有Encode'
实例,才能由泛型Encode'
进行编码。编译器不知道(也不知道)没有Generic
的Rep
未被Encode'
实例覆盖。Generic
实例的作者可以为他们的Rep
使用一个甚至还不存在的类型
您需要将请求的Encode'(Rep a)
约束添加到默认编码的上下文中
default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
将默认类型签名更改为default encode::(Generic a,encode'(Rep a))=>a->[Bool]
即使编译器确实知道一些事情,Haskell也坚持约束(可能会导致运行时簿记成本)是明确的。