How to use assert in OCaml?

China☆狼群 提交于 2019-12-07 03:08:22

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/21567318/how-to-use-assert-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!