为什么Haskell不能对Num
类型执行模式匹配,而不需要我们指定Eq
作为一个类型类呢?
例如:
h :: Num a => a -> a
h 0 = -1
h x = x + 1
当编译此函数时,ghci
报错:
* Could not deduce (Eq a) arising from the literal `0'
from the context: Num a
bound by the type signature for:
h :: forall a. Num a => a -> a
at functions.hs:9:1-20
Possible fix:
add (Eq a) to the context of
the type signature for:
h :: forall a. Num a => a -> a
* In the pattern: 0
In an equation for `h': h 0 = - 1
|
10 | h 0 = -1
| ^
将函数定义更改为以下内容即可编译并运行完美:
h :: (Num a, Eq a) => a -> a
h 0 = -1
h x = x + 1
*Main> h 0
-1
*Main>
==0
以检查您的模式,因为0
是“Num a => a”,而不是数据构造函数。 - Ry-