Haskell运算符与函数优先级 [英] Haskell operator vs function precedence
问题描述
我正在尝试为自己验证Haskell中的运算符和函数优先级。例如,以下代码
list = map foo $ xs
可以改写为
list =(map foo)$ (xs)
并且最终将会是
list = map foo xs
我的问题曾经是,为什么第一个公式不会被改写为:
list =(map foo $)xs
$ c $因为函数优先级总是高于运算符优先级,但我认为我已经找到了答案:运算符根本不被允许为函数的参数(当然,如果你用圆括号包围它们)。这是正确的吗?如果是这样,我觉得很奇怪,在RWH中没有提到这个机制/规则,或者学习你是一个Haskell,或者我搜索过的任何其他地方。所以,如果你知道一个地方,规则的地方,请链接到它。
- 编辑:感谢您的快速解答。我认为我的困惑来自于认为运算符文字会以某种方式评估某些东西,而这些东西可能会被某个函数用作参数。它帮助我记住,一个中缀操作符可以被机械地转换为前缀函数。这样做到第一个配方产生了
$ p $ ($)(map foo)(xs)
$ c $ ($)是消费函数,并且由于两个公式是等价的,所以第一个公式中的$字面值不能被地图消耗。
解决方案你是对的。此规则是由 Haskell报告定义的Haskell语法的一部分。特别要注意的是,在表达式中,函数应用的参数( fexp
)必须是 aexp
。 aexp允许运算符作为段的一部分,也可以在括号内的表达式中使用,但不能包含在运算符中。
$ b 在 map foo $ xs
,Haskell语法意味着它被解析为应用于二元运算符 $
的两个表达式。正如sepp2k所指出的那样,语法(map foo $)
是一个左侧部分,意思是不同的。
I必须承认我从来没有想过这件事,实际上不得不在报告中查看它,看看为什么运营商有他们的行为。
I am trying to verify something for myself about operator and function precedence in Haskell. For instance, the following code
list = map foo $ xs
can be rewritten as
list = (map foo) $ (xs)
and will eventually be
list = map foo xs
My question used to be, why the first formulation would not be rewritten as
list = (map foo $) xs
since function precedence is always higher than operator precedence, but I think that I have found the answer: operators are simply not allowed to be arguments of functions (except of course, if you surround them with parentheses). Is this right? If so, I find it odd, that there is no mention of this mechanic/rule in RWH or Learn you a Haskell, or any of the other places that I have searched. So if you know a place, where the rule is stated, please link to it.
-- edit: Thank you for your quick answers. I think my confusion came from thinking that an operator literal would somehow evaluate to something, that could get consumed by a function as an argument. It helped me to remember, that an infix operator can be mechanically translated to a prefix functions. Doing this to the first formulation yields
($) (map foo) (xs)
where there is no doubt that ($) is the consuming function, and since the two formulations are equivalent, then the $ literal in the first formulation cannot be consumed by map.
解决方案 You are correct. This rule is part of the Haskell syntax defined by the Haskell Report. In particular note in Section 3, Expressions, that the argument to function application (an fexp
) must be an aexp
. An aexp allows operators as part of sections, and also within a parenthesized expression, but not bare operators.
In map foo $ xs
, the Haskell syntax means that this is parsed as two expressions which are applied to the binary operator $
. As sepp2k notes, the syntax (map foo $)
is a left section and has a different meaning.
I have to confess I've never thought much about this and actually had to look it up in the Report to see why operators have the behavior they do.
这篇关于Haskell运算符与函数优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!