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

问题描述 投票:2回答:1

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

我假设IntegerexpressionTypeSigValue类型是默认类型的结果(如果我错了,请纠正我)。但是我不明白为什么不需要解释器以相同的方式处理两种类型的签名。有人可以解释一下吗?

haskell types ghc
1个回答
1
投票

这是行动中的单态性限制。在第一个示例中,您要指定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
© www.soinside.com 2019 - 2024. All rights reserved.