如预期的那样,可以正常工作:
valFrac :: Fractional a => a
valFrac = undefined
fNum :: Num a => a -> a
fNum a = undefined
resFrac :: Fractional a => a
resFrac = fNum valFrac -- Works as expected because every
-- Fractional is also a Num.
-- So as expected, we can pass
-- a Fractional argument into
-- a Num parameter.
Run Code Online (Sandbox Code Playgroud)
另一方面,以下方法也适用。我不明白为什么。
fFrac :: Fractional a => a -> a
fFrac a = undefined
valNum :: Num a => a
valNum …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个简单的功能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 …Run Code Online (Sandbox Code Playgroud)