我在为以下代码找到合适的类型约束时遇到问题
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
import GHC.Generics
data Value = One | Two deriving Generic
class Class a where
cname :: a -> String -> Bool
default cname :: (Generic a, GClass (Rep a))
=> a -> String -> Bool
cname = gname . from
class GClass f where
gname :: f a -> String -> Bool
instance GClass (f :+: g) where
gname (L1 x) s | conName (from x) == s = True
| otherwise = False
gname (R1 x) s | conName (from x) == s = True
| otherwise = False
它失败了
No instance for (Generic (f a)) arising from a use of `from'
gname
像这样添加约束
instance (Generic (f a)) => GClass (f :+: g) where
失败了
Could not deduce (Generic (f a1)) arising from a use of `from'
from the context (Generic (f a))
编辑:完整片段的完整错误消息
Generic.hs:19:31:
No instance for (Generic (f a)) arising from a use of `from'
Possible fix: add an instance declaration for (Generic (f a))
In the first argument of `conName', namely `(from x)'
In the first argument of `(==)', namely `conName (from x)'
In the expression: conName (from x) == s
Generic.hs:21:31:
No instance for (Generic (g a)) arising from a use of `from'
Possible fix: add an instance declaration for (Generic (g a))
In the first argument of `conName', namely `(from x)'
In the first argument of `(==)', namely `conName (from x)'
In the expression: conName (from x) == s
这是 GHC 7.6.3