Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use assert in OCaml?

Tags:

assert

ocaml

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?

like image 717
Zameer Manji Avatar asked Feb 05 '14 02:02

Zameer Manji


People also ask

What does assert do in OCaml?

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 .

What does :: mean in Ocaml?

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.


1 Answers

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)
like image 195
Jeffrey Scofield Avatar answered Sep 18 '22 13:09

Jeffrey Scofield