我刚开始用 Haskell 编程,我正在解决99 个 Haskell 问题,当我几乎完成第 10 个问题时,我遇到了这个问题:
-- Exercise 9
pack :: Eq a => [a] -> [[a]]
pack [] = []
pack list = let (left,right) = span (== head list) list in
left : pack right
-- Exercise 10
encode :: (Eq a, Integral c) => [a] -> [(c, a)]
encode [] = []
encode list = map (\x -> (length x, head x)) (pack list)
-- this doesn't work ^^^^^^^^
产生的错误告诉我
Could not deduce (c ~ Int)
from the context (Eq a, Integral c)
bound by the type signature for
encode :: (Eq a, Integral c) => [a] -> [(c, a)]
at C:\fakepath\ex.hs:6:11-47
`c' is a rigid type variable bound by
the type signature for
encode :: (Eq a, Integral c) => [a] -> [(c, a)]
at C:\fakepath\ex.hs:6:11
In the return type of a call of `length'
In the expression: length x
In the expression: (length x, head x)
我已经设法通过插入一个我在Learn you a Haskell中读到的函数来解决这个问题:fromIntegral
。
encode list = map (\x -> (fromIntegral $ length x, head x)) (pack list)
所以,我的问题是,为什么需要这样做?
我已经运行:t length
并得到了[a] -> Int
,这对我来说是一个非常定义的类型,它应该满足Integral c
约束。