简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM