【问题标题】:Why does one these functions fail with a type error, while the other doesn't?为什么这些函数中的一个会因类型错误而失败,而另一个却不会?
【发布时间】:2014-11-14 07:23:25
【问题描述】:

在 GHCi 中,如果我这样定义两个函数:

> let succ = (+ 1)
> let pred = (- 1)

然后调用它们,像这样:

> succ 5
> pred 5

为什么一个 (succ) 运行正常,而另一个失败并出现以下错误?

<interactive>:3:1:
Could not deduce (Num (a0 -> t))
  arising from the ambiguity check for ‘it’
from the context (Num (a -> t), Num a)
  bound by the inferred type for ‘it’: (Num (a -> t), Num a) => t
  at <interactive>:3:1-6
The type variable ‘a0’ is ambiguous
When checking that ‘it’
  has the inferred type ‘forall a t. (Num (a -> t), Num a) => t’
Probable cause: the inferred type is ambiguous

是什么导致类型推断在一个函数而不是另一个函数中失败?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    - 在 Haskell 中有一个奇怪的特殊语法规则。它是唯一不能用作左中缀部分的中缀,而-x 将始终被解析为单个负数。该符号仅在以下情况下被识别为中缀

    • 明确用作减法,2-1
    • 用作右侧部分,(1-)
    • 用作二元前缀函数,(-) 1。

    【讨论】:

    • 嗯。这似乎确实是正在发生的事情。谢谢! (另外,我刚刚注意到我当前的无点版本pred 实际上并没有达到我想要的效果。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2016-06-25
    • 2017-09-23
    • 2022-01-08
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多