[英]Haskell throws an error while specifying the type of a parameter
我刚刚开始学习Haskell。 我正在尝试实现一个将数字作为输入的函数,并根据其值返回-1、0或1。 输入可以是任何数字(整数或浮点数)。 这是代码:
signum :: (Num a) => a -> Int
signum x
| x > 0 = 1
| x < 0 = -1
| otherwise = 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.
这个错误是什么意思?
方法>
是在Ord
类中定义的,因此您需要在类型签名中添加一个附加约束:
signum :: (Ord a, Num a) => a -> Int
在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
[...]
或者,您可以检查方法本身:
*Main> :i (>)
class Eq a => Ord a where
...
(>) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 >
原始signum
没有此约束的原因是因为它不使用Ord
的方法。 相反,它使用专用于有问题的类型的函数(例如ltInt
)或模式直接匹配(请参见Word
实例): https : ltInt
Num.html#signum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.