[英]How do I use a module and a script in the terminal command ocaml?
I'm trying to run a.ml script, test.ml
, using the command ocaml
and use a module, template.ml
, that I setup.我正在尝试使用命令ocaml
运行 a.ml 脚本test.ml
并使用我设置的模块template.ml
。
Currently, I know that I can run ocaml using the module by doing ocaml -init template.ml
and that I can run a script using ocaml test.ml
.目前,我知道我可以通过执行ocaml -init template.ml
使用该模块运行 ocaml,并且我可以使用ocaml test.ml
运行脚本。
I'm trying to run the script, test.ml, and use the module, template.ml.我正在尝试运行脚本 test.ml,并使用模块 template.ml。
I have tried using ocaml test.ml
with the first line being open Template;;
我尝试使用ocaml test.ml
,第一行是open Template;;
after compiling template with ocamlopt -c template.ml
.使用ocamlopt -c template.ml
编译模板后。 Template is undefined in that case.在这种情况下,模板是未定义的。
I have also tried using ocaml -init template.ml test.ml
with and without open Template;;
我也尝试过使用ocaml -init template.ml test.ml
有和没有open Template;;
as the first line of code.作为第一行代码。 They don't work or error respectively.它们分别不起作用或出错。
First, the open
command is only for controlling the namespace.首先, open
命令仅用于控制命名空间。 Ie, it controls the set of visible names.即,它控制可见名称的集合。 It doesn't have the effect (as is often assumed) of locating and making a module accessible.它没有定位和使模块可访问的效果(通常假设)。 (In general you should avoid over-using open
. It's never necessary; you can always use the full Module.name
syntax.) (一般来说,你应该避免过度使用open
。从来没有必要;你总是可以使用完整的Module.name
语法。)
The ocaml
command line takes any number of compiled ocaml modules followed by one ocaml (.ml) file. ocaml
命令行采用任意数量的已编译 ocaml 模块,后跟一个 ocaml (.ml) 文件。
So you can do what you want by compiling the template.ml file before you start:因此,您可以在开始之前通过编译 template.ml 文件来做您想做的事情:
$ ocamlc -c template.ml
$ ocaml template.cmo test.ml
Here is a fully worked example with minimal contents of the files:这是一个完整的示例,文件内容最少:
$ 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
For what it's worth I think of OCaml as a compiled language rather than a scripting language.对于它的价值,我认为 OCaml 是一种编译语言而不是脚本语言。 So I usually compile all the files and then run them.所以我通常编译所有文件然后运行它们。 Using the same files as above, it looks like this:使用与上面相同的文件,它看起来像这样:
$ ocamlc -o test template.ml test.ml
$ ./test
19
I only use the ocaml
command when I want a to interact with an interpreter (which OCaml folks have traditionally called the "toplevel").当我想与解释器交互时,我只使用ocaml
命令(OCaml 人传统上将其称为“顶层”)。
$ ocaml
OCaml version 4.10.0
# let f x = x + 5;;
val f : int -> int = <fun>
# f 14;;
- : int = 19
#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.