Haskell冲突族实例声明
我尝试为两种Int类型定义一个除法函数Haskell冲突族实例声明,haskell,Haskell,我尝试为两种Int类型定义一个除法函数 class Dnum a b where type DivType a b _div::a->b-> DivType a b instance Dnum Int Integer where type DivType Int Integer = Integer _div a b = div (fromIntegral a) b instance Dnum Int Int where type Div
class Dnum a b where
type DivType a b
_div::a->b-> DivType a b
instance Dnum Int Integer where
type DivType Int Integer = Integer
_div a b = div (fromIntegral a) b
instance Dnum Int Int where
type DivType Int Int = Integer
_div x y = div (fromIntegral x) (fromIntegral y)
instance (Num a) => Dnum a a where
type DivType a a = a
_div x y = div x y
以下是我的主要观点:
main = do
let n = 3::Int
print $ _div n n
出现错误:
Conflicting family instance declarations:
DivType Int Int = Integer -- Defined at MyLib.hs:67:10
DivType a a = a -- Defined at MyLib.hs:71:10
|
67 | type DivType Int Int = Integer
在我看来,这个函数
\u div Int
有一些问题,我不知道为什么它会说“冲突的家庭实例”,
但是\u div Int Integer
完全没有问题
有人知道如何解决吗?问题是第67行和第71行的类型族实例重叠,因为在第67行您断言
DivType Int Int=Integer
,但在第71行您说对于任何Num a
,DivType a=a
,这特别意味着DivType Int=Int
,因此不清楚如何解决DivType Int
相反,
DivType Int Integer
不与任何内容重叠,因为DivType a a
要求两种类型匹配。问题在于第67行和第71行的实例族实例重叠,因为在第67行您断言DivType Int=Integer
,但是在第71行,你说对于任何numa
,DivType a=a
,这意味着特别是DivType Int=Int
,因此不清楚如何解析DivType Int
相反,
DivType Int Integer
不与任何内容重叠,因为DivType a a
要求两种类型匹配。您单独发布的代码不会产生此错误。更具体地说,如果第67行确实有type DivType Int=Integer
,那么第71行的DivType a=a
的上下文是什么?我猜您有一个更通用的Dnum
实例,该实例Int
/Int
也匹配,编译器无法确定使用哪个实例;这里的运行良好并输出1。抱歉,我错过了代码的实例,现在它应该会产生错误。我忘记了这方面的技术原因,但编译器根本不能(或没有)试着找出Dnum Int Int
比Num a=>Dnum a a
更具体,并且应该是首选。您单独发布的代码不会产生此错误。更具体地说,如果第67行确实有type DivType Int=Integer
,那么第71行的DivType a=a
的上下文是什么?我猜您有一个更通用的Dnum
实例,该实例Int
/Int
也匹配,编译器无法确定使用哪个实例;很抱歉,我错过了代码的实例,现在它应该会产生错误。我忘记了这方面的技术原因,但编译器无法(或没有)尝试找出Dnum Int Int
比Num a=>Dnum a
更具体,应该是首选。