我是来自 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 就在我在 main 的列表理解中的 let 绑定中使用 fromIntegral 之前。我仍在尝试习惯 ghc 的错误消息。我无法破译这个特定的内容,以便弄清楚我需要更改哪些内容才能编译我的代码。任何帮助将不胜感激。谢谢。