Haskell 用数字输入歧义
在玩Haskell交互式提示符(ghci)时,我发现了一些奇怪的东西。以下代码在ghci 7.0.4下运行Haskell 用数字输入歧义,haskell,types,Haskell,Types,在玩Haskell交互式提示符(ghci)时,我发现了一些奇怪的东西。以下代码在ghci 7.0.4下运行 [minBound..1] 引发以下异常: <interactive>:1:12: Ambiguous type variable `t0' in the constraints: (Num t0) arising from the literal `1' at <interactive>:1:12 (Enum t0) arisin
[minBound..1]
引发以下异常:
<interactive>:1:12:
Ambiguous type variable `t0' in the constraints:
(Num t0) arising from the literal `1' at <interactive>:1:12
(Enum t0) arising from the arithmetic sequence `minBound .. 1'
at <interactive>:1:1-13
(Bounded t0) arising from a use of `minBound'
at <interactive>:1:2-9
Probable fix: add a type signature that fixes these type variable(s)
In the expression: 1
In the expression: [minBound .. 1]
In an equation for `it': it = [minBound .. 1]
:1:12:
约束中不明确的类型变量“t0”:
(Num t0)源于1:12处的文字“1”
(枚举t0)由算术序列'minBound..产生。。1'
时间:1:1-13
(有界t0)因使用“minBound”而产生
时间:1:2-9
可能修复:添加修复这些类型变量的类型签名
在表达式中:1
在表达式中:[minBound..1]
在‘it’的等式中:it=[minBound..1]
我知道,将上述内容写成[minBound..1::Int]可以清楚地表明这里的“1”是一个Int,但我的问题是,歧义在哪里?”1'可以解释为Int、整数、浮点或双精度,但除Int外,所有这些都不属于有界类。那么,literal 1还可以伪装成另一个类吗?如果不是,那么怎么办?根据,如果
- 所有约束的形式均为
ca
在约束中不作为类型构造函数的参数出现,并且a
- 所涉及的类中至少有一个是数值类,并且
- 所有类都在Prelude或标准库中定义
[minBound..1]
的推断类型为
[minBound .. 1] :: (Num a, Enum a, Bounded a) => [a]
因此,默认规则适用。但对于默认,只考虑模块默认声明中列出的类型-在没有默认声明的情况下,假定默认值为(整数,双精度)
,即,要解决受约束的不明确类型变量,首先尝试整数
,如果这不满足所有约束,Double
已尝试。如果这也不满足所有约束,则默认设置失败,编译失败,类型变量不明确
在本例中,Integer
和Double
都不满足Bounded
约束,因此默认设置失败
在ghci中,或在启用了扩展默认规则的情况下,如果约束中没有数字类,但
Show
是,则也会尝试默认,默认默认值扩展为()
回答得好,谢谢;我在假设Haskell的类型推断是如何工作的,现在我知道得更清楚了