我正在尝试实现一个简单的功能totient:
coprime :: Integral a => a -> a -> Bool
coprime a b = gcd a b == 1
totient :: Integral a => a -> a
totient m = length $ filter (coprime m) [1..m-1]
ghci> :load 99problems.hs
[1 of 1] Compiling Main ( 99problems.hs, interpreted )
99problems.hs:250:13: error:
• Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
totient :: forall a. Integral a => a -> a
at 99problems.hs:249:12
• In the expression: length $ filter (coprime m) [1 .. m - 1]
In an equation for ‘totient’:
totient m = length $ filter (coprime m) [1 .. m - 1]
• Relevant bindings include
m :: a (bound at 99problems.hs:250:9)
totient :: a -> a (bound at 99problems.hs:250:1)
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
我试图用这样的东西fromIntegral或toInteger上(m-1)但没有它已经奏效。我不确定这里缺少什么...似乎Int应该是type Integral a => a。怎么了
类型Integral a => a -> a说:
a。a是的实例Integral。a。a。但是,在这种情况下,实施者会产生一个Int。每当调用者选择a作为Integralnot 的实例时Int,这将与调用者的类型不匹配。