How to use assert in OCaml?

I am trying to learn OCaml and am having trouble approving a statement. In the interpreter, I can use it:

Zameers-MacBook-Air:~ zmanji$ ocaml
        OCaml version 4.01.0

# let x = 1;;
val x : int = 1
# assert(x > 2);;
Exception: Assert_failure ("//toplevel//", 1, 0).
# ^D

However, when I put the code in a file that looks like this:

let x = 1
assert(x > 2)

I get the following error:

Zameers-MacBook-Air:Q4 zmanji$ ocaml test.ml
File "test.ml", line 2, characters 0-6:
Error: Syntax error

What am I doing wrong?

+4
source share
1 answer

If you put ;;in a file, it will work. Without this, it does not make sense syntactically. An expression 1followed by a keyword assertdoes not make sense.

I don’t particularly like using it ;;in actual code (not at the top level, i.e. on the interpreter). If you also wanted to avoid this, you could write

let x = 1
let () = assert (x > 2)
+9
source

Source: https://habr.com/ru/post/1525343/


All Articles