为什么这不完全起作用?
sum :: (Num a, Num b) => a -> b -> c
sum a b = a + b
可以肯定的是,错误消息与签名有关,但我仍然不明白原因。
Couldn't match expected type ‘a’ with actual type ‘b’
‘b’ is a rigid type variable bound by
the type signature for:
sum :: forall a b c. (Num a, Num b) => a -> b -> c
‘a’ is a rigid type variable bound by
the type signature for:
sum :: forall a b c. (Num a, Num b) => a -> b -> c
In the second argument of ‘(+)’, namely ‘b’
In the expression: a + b
In an equation for ‘sum’: sum a b = a + b
我想念什么?
由于该(+)
函数具有签名:
(+) :: Num a => a -> a -> a
因此,这意味着该(+)
函数要求操作数具有相同的类型,并且结果与操作数具有相同的类型。
您的签名意味着程序员可以选择任何Num
类型作为第一个操作数,并选择任何Num
类型作为第二个操作数,然后构造任何类型。因此,这意味着我可以将函数专用于sum :: Int -> Float -> Char
,但是没有这样的(+)
定义。
我们可以使类型更灵活,例如通过使用fromIntegral :: (Integral a, Num b) => a -> b
:
integralSum :: (Integral i, Integral j, Num c) => i -> j -> c
integralSum x y = fromIntegral x + fromIntegral y
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句