如何在终端命令 ocaml 中使用模块和脚本?

How do I use a module and a script in the terminal command ocaml?

我正在尝试 运行 .ml 脚本 test.ml,使用命令 ocaml 并使用我设置的模块 template.ml

目前,我知道我可以 运行 通过执行 ocaml -init template.ml 使用模块的 ocaml 并且我可以 运行 使用 ocaml test.ml.[=24= 的脚本] 我正在尝试 运行 脚本 test.ml,并使用模块 template.ml。

在使用 ocamlopt -c template.ml 编译模板后,我尝试使用 ocaml test.ml,第一行是 open Template ;;。在这种情况下,模板未定义。
我也尝试过使用 ocaml -init template.ml test.mlopen Template ;; 作为第一行代码。它们分别不起作用或出错。

首先,open命令仅用于控制命名空间。即,它控制可见名称集。它没有定位和使模块可访问的效果(通常假设)。 (一般来说,你应该避免过度使用 open。这从来没有必要;你总是可以使用完整的 Module.name 语法。)

ocaml 命令行接受任意数量的已编译 ocaml 模块,后跟一个 ocaml (.ml) 文件。

所以你可以在开始之前通过编译template.ml文件来做你想做的事:

$ ocamlc -c template.ml
$ ocaml template.cmo test.ml

这是一个完整的示例,文件内容最少:

$ cat template.ml
let f x = x + 5
$ cat test.ml
let main () = Printf.printf "%d\n" (Template.f 14)

let () = main ()
$ ocamlc -c template.ml
$ ocaml template.cmo test.ml
19

就其价值而言,我认为 OCaml 是一种编译语言而不是脚本语言。所以我通常会编译所有文件,然后 运行 它们。使用与上面相同的文件,它看起来像这样:

$ ocamlc -o test template.ml test.ml
$ ./test
19

我只在需要与解释器交互时使用 ocaml 命令(OCaml 人员传统上将其称为 "toplevel")。

$ ocaml
        OCaml version 4.10.0

# let f x = x + 5;;
val f : int -> int = <fun>
# f 14;;
- : int = 19
#