从整数类型创建列表时出现类型错误

zli*_*zli 1 haskell integer

我正在尝试实现一个简单的功能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)

我试图用这样的东西fromIntegraltoInteger(m-1)但没有它已经奏效。我不确定这里缺少什么...似乎Int应该是type Integral a => a。怎么了

Dan*_*ner 5

类型Integral a => a -> a说:

  1. 呼叫者可以选择一种类型a
  2. 呼叫者必须证明a是的实例Integral
  3. 呼叫者必须提供type的值a
  4. 实现者产生另一个type值a

但是,在这种情况下,实施者会产生一个Int。每当调用者选择a作为Integralnot 的实例时Int,这将与调用者的类型不匹配。