Haskell默认与表达式类型签名的交互



如果我在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

最新更新