为什么我使用GHC.Generics得到一个不明确的类型变量错误?
我已经试过这个例子了 即:为什么我使用GHC.Generics得到一个不明确的类型变量错误?,generics,haskell,ghc,Generics,Haskell,Ghc,我已经试过这个例子了 即: import GHC.Generics {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignaturesGeneric #-} data Bin = O | I deriving Show data UserTree a = Node a (UserTree a) (UserTree a) | Leaf deriving Generic class GSerialize f where gpu
import GHC.Generics
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DefaultSignaturesGeneric #-}
data Bin = O | I deriving Show
data UserTree a = Node a (UserTree a) (UserTree a) | Leaf deriving Generic
class GSerialize f where
gput :: f a -> [Bin]
instance GSerialize U1 where
gput U1 = []
instance (GSerialize a, GSerialize b) => GSerialize (a :*: b) where
gput (x :*: y) = gput x ++ gput y
instance (GSerialize a, GSerialize b) => GSerialize (a :+: b) where
gput (L1 x) = O : gput x
gput (R1 x) = I : gput x
instance (GSerialize a) => GSerialize (M1 i c a) where
gput (M1 x) = gput x
instance (Serialize a) => GSerialize (K1 i a) where
gput (K1 x) = put x
我用调用测试了函数:
toserialize Leaf
在此,编译器给出一条错误消息:
Ambiguous type variable `a0' in the constraint:
(Serialize a0) arising from a use of `toserialize'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: serialize Leaf
In an equation for `it': it = toserialize Leaf
这里缺少什么?问题是,由于
UserTree a
中的类型变量a
根本不出现在叶
构造函数中,GHC无法确定您想要哪个a
作为值。您可以通过添加显式类型签名(如
toserialize (Leaf :: UserTree Int)
更新:示例toserialize(Node 2 Leaf)
挂起,因为Int
的通用表示是递归的
type Rep Int = D1 D_Int (C1 C_Int (S1 NoSelector (Rec0 Int)))
对于没有“普通”构造函数的“基本”类型,通常必须手动定义实例。然而,由于例如Bool
是
data Bool = True | False
这适用于泛型序列化实例
toserialize (Node True Leaf Leaf)
非常感谢你的支持。但是现在我有一个永无止境的循环,如果我用“toSerialize(Node 2 Leaf)”调用函数,我想这是因为:“instance(Serialize a)=>GSerialize(K1 I a),其中gput(K1 x)=put x'Oh,是的,我在Generics.hs文件中看到了关于字符、int的递归定义,浮动。。。我希望这不是一个愚蠢的问题,但我必须自己定义哪些实例我尝试过这样的方法:instance Serialize Int where put=[]ghc给出消息:无法将表达式中的预期类型Int->[Bin]'与表达式中的实际类型[a0]'匹配:[]在put]的等式中:put=[]在
Serialize Int'****的实例声明中,不允许使用新实例:instance Generic Int。。。
toserialize (Node True Leaf Leaf)