打开 Module_name 给出编译器错误

发布于 2024-11-17 16:18:49 字数 430 浏览 1 评论 0原文

我无法编译一个极其简单的 ocaml 程序 test2.ml,

open Test1

print_string " Hello "

其中 test1.ml 仅包含 1 行

type program = string

并且 test1.ml 已编译:

bash-3.2$ ocamlc test1.ml
bash-3.2$ ls test1.*
test1.cmi   test1.cmo   test1.ml

有人知道为什么 test1.ml 不编译吗?谢谢。

更多信息。这很奇怪,因为如果我注释掉 test2.ml 的第一行“open ...”或 如果我注释掉它的第三行“print_string...”,但它们不能共存!

I cannot compile an extremely simple ocaml program test2.ml

open Test1

print_string " Hello "

with test1.ml containing only 1 line

type program = string

And test1.ml is compiled:

bash-3.2$ ocamlc test1.ml
bash-3.2$ ls test1.*
test1.cmi   test1.cmo   test1.ml

Anyone know why test1.ml does not compile?? Thank you.

More info. It's quite strange because, test2.ml compiles if I comment out its first line "open ..." OR
if I comment out its 3rd line "print_string..." but they cannot coexist!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三人与歌 2024-11-24 16:18:49

打印您收到的错误会很有帮助。仅供参考:

File "test2.ml", line 3, characters 0-12:
Error: Syntax error

原因有点复杂。文件的正常语法是一系列顶级语句,例如类型定义、let(不带in)、模块定义/打开/包含等在。

print_string "Hello" 这样的表达式永远不会被视为顶级语句,除非含义完全明确,这 99% 的情况下需要使用 将它们与前面和后面的语句分开; ;

因此,您可以编写以下内容:

open Test1 ;;
print_string " Hello "

它会起作用。不过,大多数时候,最好通过将表达式转换为顶级 let 来保持文件干净:

open Test1
let () = print_string " Hello "

这还有一个好处是确保函数返回 unit< /code>,拥有它总是很高兴。

Printing the error you received would have been helpful. For the reference, it's:

File "test2.ml", line 3, characters 0-12:
Error: Syntax error

The reason for this is a bit complex. The normal syntax is for a file to be a sequence of top-level statements, such as type definitions, let (without in), module definition/opening/including and so on.

Expressions such as print_string "Hello" are never treated as top-level statements unless the meaning is completely unambiguous, which 99% of the time involves separating them from the previous and following statement with a ;;

So, you could write the following:

open Test1 ;;
print_string " Hello "

And it would work. Most of the time, though, it is preferable to keep the file clean by turning the expression into a top-level let:

open Test1
let () = print_string " Hello "

This also has the benefit of making sure that the function returns unit, which is always nice to have.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文