gpt4 book ai didi

haskell - Double 和 Integral 类型之间的重叠实例

转载 作者:行者123 更新时间:2023-12-04 23:50:26 25 4
gpt4 key购买 nike

我有以下类型类和实例:

class StatType a where
toDouble :: a -> Double
instance StatType Double where
toDouble = id
instance Integral a => StatType a where
toDouble = fromIntegral

avg :: StatType a => [a] -> Double
avg = undefined

但接下来的表达
*Example> avg ([1,2,3,4] :: [Double])

报告关于重叠实例的类型错误
Overlapping instances for StatType Double
arising from a use of `avg'
Matching instances:
instance StatType Double -- Defined at Example.hs:61:10
instance Integral a => StatType a -- Defined at Example.hs:63:10

类型系统无法在这两个实例之间进行选择。然而, Double不是 Integral类型。
*Example> :i Double
data Double = GHC.Types.D# GHC.Prim.Double#
-- Defined in `GHC.Types'
instance StatType Double -- Defined at Example.hs:
instance Enum Double -- Defined in `GHC.Float'
instance Eq Double -- Defined in `GHC.Classes'
instance Floating Double -- Defined in `GHC.Float'
instance Fractional Double -- Defined in `GHC.Float'
instance Num Double -- Defined in `GHC.Float'
instance Ord Double -- Defined in `GHC.Classes'
instance Read Double -- Defined in `GHC.Read'
instance Real Double -- Defined in `GHC.Float'
instance RealFloat Double -- Defined in `GHC.Float'
instance RealFrac Double -- Defined in `GHC.Float'
instance Show Double -- Defined in `GHC.Float'

我不认为 Integral其中之一或任何暗示? fromIntegral (3 :: Double)引发类型错误,因为 Double不是 Integral实例。

为什么这些重叠?

谢谢!

最佳答案

很简单,这就是 GHC works

When GHC tries to resolve, say, the constraint C Int Bool, it tries to match every instance declaration against the constraint, by instantiating the head of the instance declaration. Consider these declarations:

instance context1 => C Int a     where ...  -- (A)
instance context2 => C a Bool where ... -- (B)

GHC's default behaviour is that exactly one instance must match the constraint it is trying to resolve. For example, the constraint C Int Bool matches instances (A) and (B), and hence would be rejected; while C Int Char matches only (A) and hence (A) is chosen.

Notice that

  • When matching, GHC takes no account of the context of the instance declaration (context1 etc).


所以 ghc 看不到
instance StatType Double 
instance Integral a => StatType a

它看到
instance StatType Double 
instance StatType a

这显然是重叠的。

这样做的原因是类型类是开放的。 Integral Double没有实例现在,但有人可能会导入您的库并声明一个,此时即使检查了上下文,实例也会重叠。更糟糕的是,没有明智的方法来偏爱一个而不是另一个。

关于haskell - Double 和 Integral 类型之间的重叠实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com