Haskell中缀函数应用优先 [英] Haskell infix function application precedence

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

问题描述

f x y = x * y 。我们可以用两种方法来应用这个函数: f 5 6 ,或者,使用中缀表示法, 5`f` 6 。操作员规则是否适用于最后一个表达式?这个应用程序有什么优先权?它只是函数应用程序的另一种形式,它也会具有最高的优先级?



我想编译器会看到这种特殊的形式(由于``和/或以字母(?)开头的名称),并将其视为普通函数应用程序,而不是将其视为运算符。

解决方案

Haskell 98 Report 有一个操作员应用程序将其清除:


运算符可以是运算符符号(例如+或$$),也可以是包含在重音符号(反引号)中的
普通标识符,如
`op`。例如,不用编写前缀应用程序op x y,
就可以编写中缀应用程序x`op` y。如果没有为`op'给出固定性声明
,那么它默认为最高优先级并留下
关联性(见第4.4.2节)。

正如其他答案所表明的那样,报告还有一节关于固定声明,允许您定义自己的固定性,例如:

  infixl 7`op` 


Let f x y = x * y. We can apply this function in two ways: f 5 6, or, using infix notation, 5 `f` 6. Do the operator rules apply to this last expression? What precedence will this application have? Is it just another form of function application, and so will it also have the highest precedence?

I suppose that the compiler sees this special form (due to `` and/or the name starting with a letter(?)), and actually treats this as ordinary function application, instead of considering it an operator.

解决方案

The Haskell 98 Report has a section on Operator Applications that clears it up:

An operator is either an operator symbol, such as + or $$, or is an ordinary identifier enclosed in grave accents (backquotes), such as `op`. For example, instead of writing the prefix application op x y, one can write the infix application x `op` y. If no fixity declaration is given for `op` then it defaults to highest precedence and left associativity (see Section 4.4.2).

As indicated by the other answers, the Report also has a section on Fixity Declarations that allows you to define your own fixity, for example:

infixl 7 `op`

这篇关于Haskell中缀函数应用优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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