我剛剛在Haskell開始編程,而我解決99 Haskell problems,當我幾乎與10日一樣,我以前遇到過這樣的問題:爲什麼Integral約束需要從整體調用長度?
-- 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
約束條件。
只是一個提示:我不認爲你需要'encode [] = []'case,因爲'pack [] = []'和'map _ [] = []'。 –