我是來自C++和Java背景的Haskell的新手。有時候,我對Haskell的類型系統有困難。我現在的錯誤是這段代碼:允許綁定的模糊類型變量
countIf :: (Integral b) => [a] -> (a -> Bool) -> b
countIf [] p = 0
countIf (x:xs) p
| p x = 1 + countIf xs p
| otherwise = countIf xs p
isRelativelyPrime :: (Integral a) => a -> a -> Bool
isRelativelyPrime m n = gcd m n == 1
phi :: (Integral a, Integral b) => a -> b
phi n = countIf [1..(n - 1)] (isRelativelyPrime n)
main = print [(n, phi n, ratio) | n <- [1..10], let ratio = (fromIntegral (phi n))/n]
的錯誤消息是
prog.hs:13:60:
Ambiguous type variable `b' in the constraints:
`Fractional b' arising from a use of `/' at prog.hs:13:60-85
`Integral b' arising from a use of `phi' at prog.hs:13:75-79
Probable fix: add a type signature that fixes these type variable(s)
13:60只是fromIntegral在讓主我的名單理解結合使用之前。我仍然在嘗試習慣ghc的錯誤信息。我無法破譯這個特定的一個,以找出我需要改變以獲得我的代碼進行編譯。任何幫助將不勝感激。謝謝。
您的'countIf'可以定義爲標準函數的組合:'countIf = length。翻轉過濾器'。 – demi