[英]Haskell throws an error while specifying the type of a parameter
I just started learning Haskell. 我刚刚开始学习Haskell。 I'm trying to implement a function which takes a number as it's input, and return -1, 0 or 1 depending on it's value. 我正在尝试实现一个将数字作为输入的函数,并根据其值返回-1、0或1。 The input can be any number (integer or a floating point). 输入可以是任何数字(整数或浮点数)。 Here is the code: 这是代码:
signum :: (Num a) => a -> Int
signum x
| x > 0 = 1
| x < 0 = -1
| otherwise = 0
But when I try to load it into ghci , it shows the following error: 但是,当我尝试将其加载到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.
What does this error mean? 这个错误是什么意思?
The method >
is defined in the Ord
class, so you need to add an additional constraint to your type signature: 方法>
是在Ord
类中定义的,因此您需要在类型签名中添加一个附加约束:
signum :: (Ord a, Num a) => a -> Int
In GHCi, you can view the methods of a class with :i <Class>
, for example: 在GHCi中,您可以使用:i <Class>
查看类的方法,例如:
*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
[...]
Alternatively, you can check the method itself: 或者,您可以检查方法本身:
*Main> :i (>)
class Eq a => Ord a where
...
(>) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 >
The reason why the original signum
doesn't have this constraint is because it doesn't use the methods from Ord
. 原始signum
没有此约束的原因是因为它不使用Ord
的方法。 Instead, it uses functions specialized to a type in question (like ltInt
) or pattern matches directly (see the Word
instance): https://hackage.haskell.org/package/base-4.8.0.0/docs/src/GHC-Num.html#signum 相反,它使用专用于有问题的类型的函数(例如ltInt
)或模式直接匹配(请参见Word
实例): https : ltInt
Num.html#signum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.