我試圖找出最新的錯誤。似乎類型有問題,但單獨使用相同的表達方式可以正常工作。類型錯誤與分數相關
下面是代碼:
a = [9, 4, 12, 0, -6, 16] :: [Int]
qsort:: [Int] -> [Int]
qsort [] = []
qsort [x] = [x]
qsort xs = (qsort l)++(qsort r)
where m = (realToFrac(sum xs))/(realToFrac(length xs))
l = filter (<=m) xs
r = filter (>m) xs
main::IO()
main = do
print (show (qsort a))
它拋出:
main.hs:7:36:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the expression: (realToFrac (sum xs))/(realToFrac (length xs))
In an equation for `m':
m = realToFrac (sum xs)/(realToFrac (length xs))
In an equation for `qsort':
qsort xs
= (qsort l) ++ (qsort r)
where
m = realToFrac (sum xs)/(realToFrac (length xs))
l = filter (<= m) xs
r = filter (> m) xs
但是效果很好:
a = [9, 4, 12, 0, -6, 16] :: [Int]
main::IO()
main = do
print (show ( (realToFrac(sum a))/(realToFrac(length a)) ))
替代解決方案:刪除'realToFrac'和使用''總和XS'quot'長度xs''; ''''是'Integral'類型的劃分(向零捨去/舍入;'div'向-infinity舍入),並且由於'xs :: [Int]','sum xs'和'length xs'具有相同的鍵入('Int'),以便在沒有轉換的情況下運行。 – 2013-02-18 18:37:26