I am trying to learn OCaml and I am having trouble with the assertion 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?
Assertions. The expression assert e evaluates e . If the result is true , nothing more happens, and the entire expression evaluates to a special value called unit. The unit value is written () and its type is unit .
Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.
If you put the ;;
in the file it will work. Without that, it doesn't make sense syntactically. An expression 1
followed by the keyword assert
doesn't make sense.
I don't particularly like using ;;
in actual code (not at top-level, i.e., the interpreter). If you wanted to avoid it too, you could write
let x = 1
let () = assert (x > 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With