Overlapping instances for double and integral types

I have the following type and type instances:

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

But then the expression

*Example> avg ([1,2,3,4] :: [Double])

reports a type error with overlapping instances

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

The type system cannot choose between these two instances. However, Doubleit is not a type 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'

And I don’t think what is Integralmeant by one of them or something else? fromIntegral (3 :: Double)causes a type error because Doubleit is not an instance Integral.

Why do they overlap?

Thank!

+4
source share
1 answer

Simply put, this is how the GHC works.

GHC , , C Int Bool, , . :

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

GHC , . , C Int Bool (A) (B) , , ; C Int Char (A) , , (A).

,

  • GHC (context1 ..).

ghc

instance StatType Double 
instance Integral a => StatType a 

instance StatType Double 
instance StatType a 

, , .

, , , . Integral Double, - , , . , .

+7

Source: https://habr.com/ru/post/1540892/


All Articles