28

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?

nlucaroni
  • 47,556
  • 6
  • 64
  • 86
Calin
  • 1,471
  • 1
  • 15
  • 22

2 Answers2

55

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)
camlspotter
  • 566
  • 4
  • 2
  • 2
    In what part of the official doc is present this info? I couldn't find the part about right/left associativity. – Ricardo Aug 12 '11 at 13:45
  • 5
    @Ricardo: There's an operator precedence table at http://caml.inria.fr/pub/docs/manual-ocaml/expr.html (near the top). Note that it lists higher precedence operators first. – Joey Adams Apr 17 '12 at 23:58
7

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

ygrek
  • 6,656
  • 22
  • 29