2011-06-03 71 views
6

http://en.wikibooks.org/wiki/Haskell/Beginning“无实例” 错误

Prelude> let abs x = if x < 0 then -x else x 
Prelude> abs 5 
5 
Prelude> abs -3 

<interactive>:1:6: 
    No instance for (Num (a0 -> a0)) 
     arising from the literal `3' 
    Possible fix: add an instance declaration for (Num (a0 -> a0)) 
    In the second argument of `(-)', namely `3' 
    In the expression: abs - 3 
    In an equation for `it': it = abs - 3 

什么是错的例子吗?

+2

错误信息的解释,仅供将来参考:'a0 - > a0'是'abs'的类型。 (在你的ghci中键入':t abs'来查看它。)错误信息是说这个类型'a0 - > a0'不是'Num'类的一个实例,因为只有'Num'可以被减去而且在任何情况下'3'都表示第一个参数必须是'Num'中的某种类型。 (在ghci类型':t( - )'和':t 3'中查看发生了什么。)\'( - )'的第二个参数,即\'3'“中的行最具启发性:表明'-'被视为带* 2 *参数的中缀运算符,而不是一元减号。 – ShreevatsaR 2011-06-03 07:52:33

回答

14

Haskell认为你想从abs减去3,并且抱怨abs不是数字。您需要使用一元反运算符时添加括号:

abs (-3) 
+0

打我吧:) – 2011-06-03 07:30:14

+0

干杯。这些Wikibooks文档似乎在几个地方有所不同。 – zaf 2011-06-12 13:05:40

5

的解释认为你的意思是不是abs - 3abs (-3)。您需要使用括号来消除代码的歧义,并确保明确您打算使用一元“ - ”函数,而不是减法运算符。

相关问题