OCaml:为什么我不能使用此运算符中缀? [英] OCaml: Why I can't use this operator infix?

查看:91
本文介绍了OCaml:为什么我不能使用此运算符中缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个自定义的相等运算符(定义不是很重要,因此我将插入虚拟的东西):

I defined a custom equality operator (the definition is not really important so I will insert dummy stuff):

let ( ~=~ ) a b = true

如果我尝试使用中缀:

if a ~=~ b then 1 else 2

我收到以下错误:This expression is not a function; it cannot be applied.

我可以通过将运算符从~=~重命名为=~或通过将其作为函数调用来解决此问题:if (~=~) a b then 1 else 2.

I can fix this either by renaming the operator from ~=~ to =~ or by calling it as a function: if (~=~) a b then 1 else 2.

对于以~开头的运算符,这似乎是一个普遍问题. 我的问题是为什么我不能使用这样的运算符中缀? ~符号有什么特别之处吗?

This seems that is a general problem with operators that start with ~. My question is why I can't use such operators infix? Is anything special about ~ symbol?

注意:我已经阅读过文档,但是找不到任何相关的内容.也许我错过了什么?

Note: I already went through documentation but I couldn't find anything relevant. Maybe I missed something?

推荐答案

在OCaml中,运算符是中缀还是前缀取决于其第一个字符. 在这种情况下,字符〜"用于前缀:通过让(〜=〜)a b = ...,您可以定义前缀运算符. 〜=〜a是有效的表达式,并返回一个函数.

In OCaml, whether an operator is infix or prefix is determined by its first character. In you case, the character '~' is for prefix: by let (~=~) a b = ..., you are defining a prefix operator. ~=~ a is a valid expression, and returns a function.

除了中缀或前缀之外,中缀运算符的关联性(左或右)和运算符优先级(+和*中的哪个更强?)在语法上由运算符的第一个字符确定.

In addition to infix or prefix, infix operator associativity (left or right) and operator precedences (which of + and * has stronger?) are syntactically determined by the first character of the operator.

这听起来很丑陋,因为您无法控制自己喜欢的运算符的特性,但是它使具有许多奇怪的自定义运算符的其他人更容易阅读OCaml源代码.

This sounds ugly, since you cannot have control of your fancy operators characteristics, but it makes easier to read OCaml source code by someone else with lots of strange custom operators.

这是运算符的字符表:

The first char   :  prefix/infix/connectivity power/left-or-right
! ~ ?            :  prefix
= < > | & $      :  infix0, left
@ ^              :  infix1, right
+ -              :  infix2, left
* /              :  infix3, left  ( ** is exceptional. It is right assoc and have power 4)

这篇关于OCaml:为什么我不能使用此运算符中缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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