我正在阅读Type类,Chapter 2 of Learn You Haskell For Great Good。我的问题是为什么4 + 3.2有效而不是长度[1,2,3,4] + 3.2,为什么我们需要在第二种情况下使用 fromIntegral 函数。 Num 和 Integral 类型类之间没有关系。如何找到类型的实例类型?
答案 0 :(得分:3)
在这种情况下使用ghci检查类型,例如它会告诉您第一次输入:
Prelude> :t 4 + 3.2
4 + 3.2 :: Fractional a => a
此处fromInteger
是隐含的(4
)。
在第二种情况下,您遇到了问题,length
为:: [a] -> Int
(在较新的GHC中略有不同),而3.2
仍为:: Fractional a => a
但(+)
} :: Num a => a -> a -> a
(它需要相同类型的参数a
) - 现在Int
不是Fractional
的实例,而且您收到错误。
:i
本身使用GHCi:
Prelude> :i Int
data Int = GHC.Types.I# GHC.Prim.Int# -- Defined in ‘GHC.Types’
instance Bounded Int -- Defined in ‘GHC.Enum’
instance Enum Int -- Defined in ‘GHC.Enum’
instance Eq Int -- Defined in ‘GHC.Classes’
instance Integral Int -- Defined in ‘GHC.Real’
instance Num Int -- Defined in ‘GHC.Num’
instance Ord Int -- Defined in ‘GHC.Classes’
instance Read Int -- Defined in ‘GHC.Read’
instance Real Int -- Defined in ‘GHC.Real’
instance Show Int -- Defined in ‘GHC.Show’
但请记住,这取决于加载的模块 - 例如,当您import Test.QuickCheck
时,您会看到Int
现在也是Arbitrary
的实例:
Prelude Test.QuickCheck> :i Int
data Int = GHC.Types.I# GHC.Prim.Int# -- Defined in ‘GHC.Types’
instance Bounded Int -- Defined in ‘GHC.Enum’
instance Enum Int -- Defined in ‘GHC.Enum’
instance Eq Int -- Defined in ‘GHC.Classes’
instance Integral Int -- Defined in ‘GHC.Real’
instance Num Int -- Defined in ‘GHC.Num’
instance Ord Int -- Defined in ‘GHC.Classes’
instance Read Int -- Defined in ‘GHC.Read’
instance Real Int -- Defined in ‘GHC.Real’
instance Show Int -- Defined in ‘GHC.Show’
instance [overlap ok] [safe] CoArbitrary Int
-- Defined in ‘Test.QuickCheck.Arbitrary’
instance [overlap ok] [safe] Arbitrary Int
-- Defined in ‘Test.QuickCheck.Arbitrary’
答案 1 :(得分:0)
length
将其输出类型修复为Int
(与3.2
不兼容),而不是Num
。您正在寻找的功能是:
genericLength :: Num i => [b] -> i