OCaml:为什么我不能使用这个运算符中缀?
我定义了一个自定义相等运算符(定义并不重要,所以我将插入虚拟的东西):
let ( ~=~ ) a b = true
如果我尝试使用它中缀:
if a ~=~ b then 1 else 2
我收到以下错误:这个表达式不是一个函数;无法应用
。
我可以通过将运算符从 ~=~
重命名为 =~
或将其作为函数调用来解决此问题:if (~=~) ab then 1否则2。
这似乎是以 ~
开头的运算符的普遍问题。 我的问题是为什么我不能使用这样的运算符中缀? ~
符号有什么特别之处吗?
注意:我已经浏览了文档,但找不到任何相关内容。也许我错过了什么?
I defined a custom equality operator (the definition is not really important so I will insert dummy stuff):
let ( ~=~ ) a b = true
If I try to use it infix:
if a ~=~ b then 1 else 2
I get the following error:This expression is not a function; it cannot be applied
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 OCaml 中,运算符是中缀还是前缀由其第一个字符决定。
在您的情况下,字符 '~' 代表前缀:通过 let (~=~) ab = ...,您正在定义一个前缀运算符。 ~=~ a 是一个有效的表达式,并返回一个函数。
除了中缀或前缀之外,中缀运算符的结合性(左或右)和运算符优先级(+ 和 * 哪个更强?)在语法上由运算符的第一个字符决定。
这听起来很丑陋,因为您无法控制奇特的运算符特征,但它使其他人更容易阅读具有许多奇怪的自定义运算符的 OCaml 源代码。
这是运算符的字符表:
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.
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.
Here is the table of chars for operators:
根据 ocaml 的词汇约定
~
是为前缀运算符保留的,请参阅http://caml.inria.fr/pub/docs/manual-ocaml/ lex.html#infix-symbol
By lexical conventions of ocaml
~
is reserved for prefix operators, seehttp://caml.inria.fr/pub/docs/manual-ocaml/lex.html#infix-symbol