为什么Haskell将我的Num类型解释为Enum?

Zai*_*aid 2 haskell type-inference typeclass

我正在尝试在Haskell中编译以下函数,以模仿在数值列表中指定常量的多项式的区分:

diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) [0..]
Run Code Online (Sandbox Code Playgroud)

Haskell拒绝编译它,给出了以下原因:

Could not deduce (Enum a) from the context (Num a)
 arising from the arithmetic sequence `0 .. ' at fp1.hs:7:38-42
Possible fix:
 add (Enum a) to the context of the type signature for `diff'
In the third argument of `zipWith', namely `[0 .. ]'
In the expression: zipWith (*) (tail coeff) ([0 .. ])
In the definition of `diff':
diff coeff = zipWith (*) (tail coeff) ([0 .. ])
Run Code Online (Sandbox Code Playgroud)

为什么Haskell将[0..]列表视为Enum类型,我该如何解决这个问题.请记住,我想利用这里的懒惰评估,因此无限列表.

sth*_*sth 8

[0..]是语法糖enumFrom 0,在课堂上定义Enum.因为您希望生成一个a包含[0..]编译器要求a的类的列表Enum.

您可以添加Enum a函数的类型签名,也可以通过生成[0..] :: [Integer]和使用fromInteger(在类中定义Num)来获取函数的类型[a]:

diff :: (Num a) => [a] -> [a]
diff [] = error "Polynomial unspecified"
diff coeff = zipWith (*) (tail coeff) (map fromInteger [0..])
Run Code Online (Sandbox Code Playgroud)

  • 嗯,我可能写'(iterate(+1)0)`因为它更短,但最后它们都是一样的...... (2认同)

Dar*_*rio 7

diff必须是正确的类型

diff :: (Num a, Enum a) => [a] -> [a]
Run Code Online (Sandbox Code Playgroud)

因为使用[x..]需要类型来实例化Enum.