开发者

Open Module_name gives a compiler-error

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜