使用此功能:
getK x y
| y < 1 = error "Index can not be less than 1!"
| y > length x = error "Index greater than array length"
| otherwise = x !! (y-1)
如果我没有定义类型,GHC就可以了。
*Main> :info getK
getK :: [a] -> Int -> a -- Defined at main.hs:7:1
但是假设我将类型约束写为:
getK :: (Int b) => [a] -> b -> a
据我所知,以上是GHC推断的内容。但不,它会产生以下错误:
main.hs:6:10:
`Int' is applied to too many type arguments
In the type signature for `getK': getK :: Int b => [a] -> b -> a
Failed, modules loaded: none.
我的直接反应是,我没有将类型分配给&#39; a一定存在问题。 (虽然不应该因为GHC认识到&#39; a&#39;可以是任何类型。所以我尝试了:
getK :: (Num a, Ord a, Int b) => [a] -> b -> a
另一个错误......
main.hs:6:24:
`Int' is applied to too many type arguments
In the type signature for `getK':
getK :: (Num a, Ord a, Int b) => [a] -> b -> a
请帮助我理解这里的行为。
答案 0 :(得分:2)
Int
是一种类型,而不是类型类。只有像Num
和Ord
这样的类型才能用作类型约束。这就是你的签名的写法:
getK :: [a] -> Int -> a
GHCI有一个:info
命令(可以缩写为:i
),它会告诉您有关类型和类型类的信息,并比较它对Int
与其所说内容的说法Num
:
λ> :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’
λ>
λ>
λ> :i Num
class Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- Defined in ‘GHC.Num’
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Int -- Defined in ‘GHC.Num’
instance Num Float -- Defined in ‘GHC.Float’
instance Num Double -- Defined in ‘GHC.Float’