【问题标题】:Type ambiguity with numbers用数字输入歧义
【发布时间】:2012-04-23 20:08:45
【问题描述】:

我在玩 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' 可以解释为 IntIntegerFloatDouble,但除了 >Int 属于 Bounded 类。那么文字 1 是否可以伪装成另一个类?如果不是,那是什么?

【问题讨论】:

    标签: haskell types


    【解决方案1】:

    根据defaulting rules,如果

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

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

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

    所以默认规则适用。但是对于默认设置,仅考虑模块的 默认声明 中列出的类型 - 在没有默认声明的情况下,假定 (Integer, Double)默认默认,即要解决受约束的模糊类型变量,首先尝试Integer,如果不满足所有约束,则尝试Double。如果这也不满足所有约束,则默认失败并且编译失败并出现ambiguous type variable 错误¹。

    在目前的情况下,IntegerDouble 都不满足 Bounded 约束,因此默认设置失败。

    ¹ 在 ghci 中,或启用 ExtendedDefaultRules 扩展时,如果约束中没有数字类但 Show 存在,也会尝试默认设置,并且默认默认值由 () 扩展。

    【讨论】:

    • 好答案,谢谢;我一直在假设 Haskell 的类型推断是如何工作的,现在我知道了
    猜你喜欢
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多