【发布时间】:2020-02-01 15:52:12
【问题描述】:
我在 .hs 文件中有以下代码
module TypeInference1 where
f :: Num a => a -> a -> a
f x y = x + y + 3
然后如果我检查f的类型,我得到以下结果,这是可以的:
*TypeInference1> :t f
f :: Num a => a -> a -> a
如果我将一个小数类型的参数传递给 f 并检查我获得的类型:
*TypeInference1> :t f 1.0
f 1.0 :: Fractional a => a -> a
但另一方面,如果我通过对其一个参数设置除法运算来更改 f,如下所示:
f x y = x/2 + y + 3
我收到以下错误:
5-typeInference1.hs:4:9: error:
• Could not deduce (Fractional a) arising from a use of ‘/’
from the context: Num a
bound by the type signature for:
f :: forall a. Num a => a -> a -> a
at 5-typeInference1.hs:3:1-25
Possible fix:
add (Fractional a) to the context of
the type signature for:
f :: forall a. Num a => a -> a -> a
• In the first argument of ‘(+)’, namely ‘x / 2’
In the first argument of ‘(+)’, namely ‘x / 2 + y’
In the expression: x / 2 + y + 3
为什么会发生这种情况,为什么我改变上面的函数f时不能推断出类型?
【问题讨论】:
标签: haskell