如何在OCaml中使用assert? [英] How to use assert in OCaml?

查看:123
本文介绍了如何在OCaml中使用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)

我收到以下错误:

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

我在做什么错了?

推荐答案

如果将;;放在文件中,它将起作用.没有它,它在语法上就没有意义.表达式1后跟关键字assert没有任何意义.

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)

这篇关于如何在OCaml中使用assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆