Hmmm, the manual seems to suggest that keywords can’t be overridden, and while it’s true for almost all the keywords on the list, I know for a fact that one can rebind + and *
So, while
let and x y = x && y
Isn’t valid OCaml
let ( + ) x y = x +. y
Is valid OCaml
Is the manual incorrect in this section? Should a clause be added to explain some exceptions to this rule?
You can rebind the value of the function ( + ) associated to the keyword + but you cannot make + a non-operator, nor override its meanings as a covariance annotation in
type +'a t = A
The manual warning concerns more word-like keywords, for instance then which can be confused with a normal identifier.
It appears that the lexer expects it to be an operator, but you can define it as a non-operator. For example:
let (+) = 0 in (+)
returns 0 .
While
let (+) = 0 in +
gives a syntax error, which seems to indicate that it is not accepted by the lexer.
And
let (+) = 0 in 1 + 2
gives a type error, so the lexer is fine because used as an infix operator, but then the type checker is fine redefining as an non-operator.
I am quite confused with this behaviour. Is it to be expected?
The string + is always accepted by the lexer as an operator token.
On the parser side, LPAREN operator RPAREN is a valid syntax for the identifier associated to the operator.
Contrarily, operator alone without operand is not a valid syntax and will be rejected by the parser.
You are free to define identifier however you want, the typechecker will not check if your definition is compatible with using it as infix operator before you try to use it as such.