我是具有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的错误消息。我无法破译这一特定代码,以便弄清楚我需要更改什么才能编译我的代码。任何帮助将不胜感激。谢谢。
最佳答案
您还需要在n上调用fromIntegral,因为Haskell不会自动从整数类型转换,因为您从fromIntegral(phi n)调用后就已经知道了。我一直在犯这个错误,没什么大不了的!