esk
esk

Reputation: 21

Using <> in an assert statement in OCaml causes error

So this might be a stupid question, but I am running into an error in utop right now after just beginning to use OCaml. I am trying to assert that two ints are structurally not equal.

assert 2 <> 3;;
Error: This expression has type int but an expression was expected of type
   bool because it is in the condition of an assertion

The entire statement causes an error, but simply typing the expression I am asserting correctly evaluates to true.

2 <> 3;;
- : bool = true

I added parentheses to the original assert statement and that fixes the problem.

assert (2 <> 3);;
- : unit = ()

I am just wondering what exactly happened without the parentheses to cause the error initially. When do you need parentheses typically?

Upvotes: 1

Views: 122

Answers (1)

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19349

This is an issue with precedence, which determines how "eagerly" a parsing rule is applied. assert has a relatively high precedence, higher than <> and other operations. This means that this expression

assert 2 <> 3

is parsed as

(assert 2) <> 3

and not as

assert (2 <> 3)

You can find the full table of precedence here: https://caml.inria.fr/pub/docs/manual-ocaml/expr.html#sec133

Upvotes: 5

Related Questions