Haskell 运算符与函数优先级 [英] Haskell operator vs function precedence

查看:24
本文介绍了Haskell 运算符与函数优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为自己验证有关 Haskell 中运算符和函数优先级的内容.比如下面的代码

I am trying to verify something for myself about operator and function precedence in Haskell. For instance, the following code

list = map foo $ xs

可以改写为

list = (map foo) $ (xs)

并且最终会

list = map foo xs

我的问题曾经是,为什么第一个公式不会被重写为

My question used to be, why the first formulation would not be rewritten as

list = (map foo $) xs

因为函数优先级总是高于运算符优先级,但我想我已经找到了答案:运算符根本不允许作为函数的参数(当然,如果你用括号将它们括起来).这是正确的吗?如果是这样,我觉得很奇怪,在 RWH 或 Learn you a Haskell 或我搜索过的任何其他地方都没有提到这个机制/规则.所以如果你知道一个地方,在那里规定了规则,请链接到它.

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)

毫无疑问,($) 是消费函数,并且由于两个公式是等价的,那么第一个公式中的 $ 字面量不能被 map 消费.

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.

推荐答案

你说得对.此规则是 Haskell Report 定义的 Haskell 语法的一部分.特别注意第 3 节,表达式,函数应用程序的参数(fexp)必须是 aexp.aexp 允许操作符作为部分的一部分,也允许在括号内的表达式中,但不能是裸操作符.

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.

map foo $ xs 中,Haskell 语法意味着这被解析为两个应用于二元运算符$ 的表达式.正如 sepp2k 所指出的,语法 (map foo $) 是左边的部分,具有不同的含义.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆