Num和Integral类型类 - Haskell

时间:2015-09-07 13:30:48

标签: haskell typeclass

我正在阅读Type类,Chapter 2 of Learn You Haskell For Great Good。我的问题是为什么4 + 3.2有效而不是长度[1,2,3,4] + 3.2,为什么我们需要在第二种情况下使用 fromIntegral 函数。 Num Integral 类型类之间没有关系。如何找到类型的实例类型?

2 个答案:

答案 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的实例,而且您收到错误。

如何查找类型为

的类 PS(最初的答案消失了) - 最简单的方法是使用: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