gpt4 book ai didi

haskell - 为什么 `-`(减号)不适用于运算符(operator)部分?

转载 作者:行者123 更新时间:2023-12-01 14:35:37 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Prefix form of unary operator in Haskell

(4 个回答)


7年前关闭。




基于该位置,Haskell 中的部分应用程序得到了正确答案。

Prelude> (/2) 10
5.0
Prelude> (2/) 10
0.2
Prelude> (+3) 10
13
Prelude> (3+) 10
13

但是,对于 - 运算符,我收到了 (-3) 的错误。正如 Haskell(似乎)将其解释为一个值 -3不是部分应用。
Prelude> (-3) 10

<interactive>:4: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>:4:1-7
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

如何解决此问题以获得 7在这个例子中?

最佳答案

使用 subtract . -是 Haskell 中唯一的运算符,它同时出现在前缀和二进制中缀变体中:

let a = -3     -- prefix  variant
let b = (-3) -- also prefix variant!
let c = 4 - 3 -- binary variant
因此,您必须使用 (subtract 3) 10 .另见 section 3.4 in the Haskell 2010 report (强调我的):

The special form -e denotes prefix negation, the only prefix operator in Haskell, and is syntax for negate (e). The binary - operator does not necessarily refer to the definition of - in the Prelude; it may be rebound by the module system. However, unary - will always refer to the negate function defined in the Prelude. There is no link between the local meaning of the - operator and unary negation.

Prefix negation has the same precedence as the infix operator - defined in the Prelude (see Table 4.1 ). Because e1-e2 parses as an infix application of the binary operator -, one must write e1(-e2) for the alternative parsing. Similarly, (-) is syntax for (\ x y -> x-y), as with any infix operator, and does not denote (\ x -> -x)— one must use negate for that.


section 3.5总结(再次强调我的):

Because - is treated specially in the grammar, (- exp) is not a section, but an application of prefix negation, as described in the preceding section. However, there is a subtract function defined in the Prelude such that (subtract exp) is equivalent to the disallowed section. The expression (+ (- exp)) can serve the same purpose.

关于haskell - 为什么 `-`(减号)不适用于运算符(operator)部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com