簡體   English   中英

如何在終端命令 ocaml 中使用模塊和腳本?

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

我正在嘗試使用命令ocaml運行 a.ml 腳本test.ml並使用我設置的模塊template.ml

目前,我知道我可以通過執行ocaml -init template.ml使用該模塊運行 ocaml,並且我可以使用ocaml test.ml運行腳本。
我正在嘗試運行腳本 test.ml,並使用模塊 template.ml。

我嘗試使用ocaml test.ml ,第一行是open Template;; 使用ocamlopt -c template.ml編譯模板后。 在這種情況下,模板是未定義的。
我也嘗試過使用ocaml -init template.ml test.ml有和沒有open 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 人傳統上將其稱為“頂層”)。

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM