Haskell在指定参数类型时抛出错误

Haskell在指定参数类型时抛出错误,haskell,ghci,Haskell,Ghci,我刚开始学哈斯克尔。我试图实现一个函数,它以一个数字作为输入,并根据其值返回-1、0或1。输入可以是任何数字(整数或浮点)。代码如下: signum :: (Num a) => a -> Int signum x | x > 0 = 1 | x < 0 = -1 | otherwise = 0 signum::(numa)=>a->Int x征 |x>0=1 |x

我刚开始学哈斯克尔。我试图实现一个函数,它以一个数字作为输入,并根据其值返回-1、0或1。输入可以是任何数字(整数或浮点)。代码如下:

signum :: (Num a) => a -> Int
signum x
    | x > 0 = 1
    | x < 0 = -1
    | otherwise = 0
signum::(numa)=>a->Int
x征
|x>0=1
|x<0=-1
|否则=0
但当我尝试将其加载到ghci时,它显示以下错误:

[1 of 1] Compiling Main             ( run_it.hs, interpreted )

run_it.hs:7:13:
Could not deduce (Ord a) arising from a use of `>'
from the context (Num a)
  bound by the type signature for Main.signum :: Num a => a -> Int
  at run_it.hs:5:11-29
Possible fix:
  add (Ord a) to the context of
    the type signature for Main.signum :: Num a => a -> Int
In the expression: x > 0
In a stmt of a pattern guard for
               an equation for `signum':
  x > 0
In an equation for `signum':
    signum x
      | x > 0 = 1
      | x < 0 = - 1
      | otherwise = 0
Failed, modules loaded: none.
[1/1]编译Main(运行\u it.hs,解释)
运行它。hs:7:13:
无法推断因使用“>”而产生的(Ord a)
从上下文(Num a)
由Main.signum::Num a=>a->Int的类型签名绑定
在跑步时。hs:5:11-29
可能的解决方案:
将(Ord a)添加到
Main.signum::Num a=>a->Int的类型签名
在表达式中:x>0
在图案保护的stmt中
“signum”的一个等式:
x>0
在‘signum’的方程式中:
x征
|x>0=1
|x<0=-1
|否则=0
失败,已加载模块:无。

这个错误是什么意思?

方法
是在
Ord
类中定义的,因此您需要向类型签名添加一个附加约束:

signum :: (Ord a, Num a) => a -> Int
在GHCi中,您可以使用
:i
查看类的方法,例如:

*Main> :i Ord
class Eq a => Ord a where
  compare :: a -> a -> Ordering
  (<) :: a -> a -> Bool
  (<=) :: a -> a -> Bool
  (>) :: a -> a -> Bool
  (>=) :: a -> a -> Bool
  [...]

原始的
signum
没有此约束的原因是它没有使用
Ord
中的方法。相反,它使用特定于所讨论类型的函数(如
ltInt
)或直接匹配的模式(参见
Word
实例):

方法
是在
Ord
类中定义的,因此需要为类型签名添加额外的约束:

signum :: (Ord a, Num a) => a -> Int
在GHCi中,您可以使用
:i
查看类的方法,例如:

*Main> :i Ord
class Eq a => Ord a where
  compare :: a -> a -> Ordering
  (<) :: a -> a -> Bool
  (<=) :: a -> a -> Bool
  (>) :: a -> a -> Bool
  (>=) :: a -> a -> Bool
  [...]

原始的
signum
没有此约束的原因是它没有使用
Ord
中的方法。相反,它使用特定于所讨论类型的函数(如
ltInt
)或直接匹配的模式(参见
Word
实例):

Num
不会在haskell中派生
Ord
。因此,您不能使用
Num
在haskell中不派生
Ord
。因此,您不能使用
非常感谢您的帮助:-)我对haskell相当陌生,这些错误消息对我来说非常难以理解!!!非常感谢您的帮助:-)我对haskell还比较陌生,这些错误消息对我来说非常神秘,我无法理解!!!