OCaml: Why I can't use this operator infix?

夙愿已清 提交于 2019-12-18 11:27:02

问题


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?


回答1:


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:

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)



回答2:


By lexical conventions of ocaml ~ is reserved for prefix operators, see http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#infix-symbol



来源:https://stackoverflow.com/questions/6150551/ocaml-why-i-cant-use-this-operator-infix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!