如果我在Haskell脚本中键入以下内容:
expressionTypeSigValue = 0 :: Integral a => a
typeSigValue :: Integral a => a
typeSigValue = 0
然后将其加载到GHCi(v。8.0.2)中,它告诉我两个常量具有不同的类型:
*Main> :t expressionTypeSigValue
expressionTypeSigValue :: Integer
*Main> :t typeSigValue
typeSigValue :: Integral a => a
我假设Integer
的expressionTypeSigValue
类型是默认类型的结果(如果我错了,请纠正我)。但是我不明白为什么不需要解释器以相同的方式处理两种类型的签名。有人可以解释一下吗?
这是行动中的单态性限制。在第一个示例中,您要指定0
的类型,而不是expressionTypeSigValue
。无论0
具有类型Integral a => a
还是其自然类型Num a => a
,单态性限制都会使其默认为Integer
。请考虑以下GHCi中的默认情况,其中默认禁用单态性:
-- Without the monomorphism restriction, the polymorphic type of the
-- value is kept.
Prelude> expressionTypeSigValue = 0 :: Integral a => a
Prelude> :t expressionTypeSigValue
expressionTypeSigValue :: Integral a => a
-- With the monomorphism restriction, the polymorphic value
-- is replaced with the default monomorphic value.
Prelude> :set -XMonomorphismRestriction
Prelude> expressionTypeSigValue = 0 :: Integral a => a
Prelude> :t expressionTypeSigValue
expressionTypeSigValue :: Integer