2012-04-23 43 views
5

我碰到了一些我在使用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) 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] 

我知道,写了上为[minBound..1 :: INT]就明确指出“ 1'的意思是Int,但我的问题是,歧义在哪里? “1”可以被解释为诠释整数浮动,但这些都不只是诠释属于类。那么还有另外一个可以伪装成字面的类吗?如果不是,那么什么?

回答

10

defaulting rules,受约束的类型变量试图通过默认来解决,如果

  • 所有约束的形式为C a; a不作为约束中类型构造函数的参数出现,并且至少涉及的其中一个类是数字类,并且所有类都在Prelude或标准库中定义。

推断型表达[minBound .. 1]的是

[minBound .. 1] :: (Num a, Enum a, Bounded a) => [a] 

所以默认规则适用。但对于违约,只有在默认声明模块的被认为是列出的类型 - 在不存在默认声明中,缺省默认假定的(Integer, Double),即以解决受约束暧昧型变量,第一Integer试图,如果不满足所有约束,则尝试Double。如果这还不能满足所有约束条件,则默认失败,并且编译失败,并显示ambiguous type variable错误¹。

在这种情况下,IntegerDouble都不符合Bounded约束条件,因此违约失败。

¹在ghci中,或与ExtendedDefaultRules扩展启用,默认如果没有数字类是限制因素,但Show是,默认的缺省值由()延长,也会尝试。

+0

很好的答案,谢谢;我正在假设Haskell的类型推断是如何工作的,现在我知道的更好 – Aky 2012-04-23 21:05:14