简体   繁体   中英

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.

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 .
I'm trying to run the script, test.ml, and use the module, template.ml.

I have tried using ocaml test.ml with the first line being open Template;; after compiling template with 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;; as the first line of code. They don't work or error respectively.

First, the open command is only for controlling the namespace. 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.)

The ocaml command line takes any number of compiled ocaml modules followed by one ocaml (.ml) file.

So you can do what you want by compiling the template.ml file before you start:

$ 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. 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 version 4.10.0

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM