从整数类型创建列表时出现类型错误 [英] type error when creating list from integral type

查看:79
本文介绍了从整数类型创建列表时出现类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的功能:totient:

I'm trying to implement a simple function: 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.

我尝试在(m-1)上使用fromIntegraltoInteger之类的东西,但没有一个起作用.我不确定我在这里缺少什么...似乎Int应该是类型Integral a => a.怎么了?

I tried using stuff like fromIntegral or toInteger on (m-1) but none of it has worked. I'm not sure what I'm missing here... it seems like Int should be a type Integral a => a. What's going wrong?

推荐答案

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

  1. 呼叫者可以选择类型a.
  2. 呼叫者必须证明aIntegral的实例.
  3. 呼叫者必须提供a类型的值.
  4. 实现器产生另一个类型为a的值.
  1. Caller gets to choose a type a.
  2. Caller must prove that a is an instance of Integral.
  3. Caller must provide a value of type a.
  4. Implementer produces another value of type a.

但是,在这种情况下,实现者生成了Int.每当调用者选择a作为不是IntIntegral的实例时,这将与调用者的类型不匹配.

However, in this case, the implementer has produced an Int. Any time the caller chooses a to be an instance of Integral that is not Int, this will not match the caller's type.

这篇关于从整数类型创建列表时出现类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆