使用递归创建一个简单的乘数,GHCI在函数类型上引发错误
mul :: Num a => a -> a -> a
mul a 1 = a
mul a n = a + mul a (n-1)
这是收到的错误消息
Could not deduce (Eq a) arising from the literal ‘1’
from the context (Num a)
bound by the type signature for mul :: Num a => a -> a -> a
at es8.hs:44:8-27
Possible fix:
add (Eq a) to the context of
the type signature for mul :: Num a => a -> a -> a
In the pattern: 1
In an equation for ‘mul’: mul a 1 = a
Failed, modules loaded: none.
我认为我必须使用params应用Number对象,因此Num a
部分是必需的。
答案 0 :(得分:5)
此约束适用于您用于定义mul
的第一个等式:
mul a 1 = a
它表示每当第二个参数等于 1
时,结果应该是第一个参数。 Num
没有Eq
超类约束,因为它可以考虑相等不可判定的数字(例如Reals)。因此,您需要按照错误消息的建议,通过手动添加该约束来进一步限制您的功能。
mul :: (Eq a, Num a) => a -> a -> a
mul a 1 = a
mul a n = a + mul a (n-1)