List of protected keyword in OCaml

Yesterday I had an error with the statement “let val = …” which is obviously false and I replaced by the correct “let ranval = …”.

What is the list of protected keywords in OCaml? A google search does not return anything and it seems legitimate to have such a list.

For other languages such as C++, the list can be found easily: https://en.cppreference.com/w/cpp/keyword

The list is in the manual: http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#sec84 .

1 Like

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?

1 Like

They aren’t keywords, that’s why.

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.

1 Like

Here’s the latest link, with working anchor:
https://v2.ocaml.org/manual/lex.html#sss:keywords

The OCaml manual also provides an Index of keywords which is helpful in reading syntaxes and mentions of keywords in detail.
https://v2.ocaml.org/manual/manual074.html

1 Like

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.

1 Like