簡體   English   中英

如何定義導出單個功能的模塊?

[英]How to define module that exports a single function?

我想學習OCaml已有很多年了,最近我決定最終學習,但是我對OCaml的第一次真正接觸並不是吉祥的。

我正在使用一組練習來學習它(這種方法對我使用其他語言非常有效)。 每個練習都附帶一個測試腳本。 第一個測試腳本是這樣的:

(* test.ml *)

open Core.Std
open OUnit2
open Mymod

let ae exp got _test_ctxt = assert_equal ~printer:String.to_string exp got

let tests = ["hello" >:: ae "hello!" (echo "hello!");]

let () =
    run_test_tt_main ("tests" >::: tests)

從字面上看 ,我整個上午都沒能工作。

我試圖找出如何在所有這些地方做到這一點:

https://realworldocaml.org/v1/en/html/files-modules-and-programs.html

http://caml.inria.fr/pub/distrib/ocaml-4.01/ocaml-4.01-refman.html

https://ocaml.org/learn/tutorials/modules.html

...以及其他幾個地方,卻沒有發現與問題相關的東西(或可行的東西)。

即使有很多關於OCaml文檔的頁面,我也找不到能告訴我如何編寫Mymod模塊的內容。

我嘗試將以下任何內容放入mymod.mli文件中:

let echo x = x ;;
let echo : string -> string = fun x -> x ;;
let echo x : string = x ;;

...以及其他數十種變體; 它們都無法編譯,更不用說通過測試了。 編譯器錯誤消息難以理解(例如: illegal begin of interf ),我找不到解釋它們的文檔。

我在文檔中都找不到用於定義僅返回其(字符串)輸入的函數的語法。

我將不勝感激。

要詳細說明@camlspotter指出的內容,您應該具有以下mymod.mli文件:

val echo : string -> string

和一個mymod.ml文件,如下所示:

let echo s = s

您可以像這樣編譯和運行:

$ ocamlopt -c mymod.mli
$ ocamlopt -c mymod.ml
$ echo 'Printf.printf "saw %s\n" (Mymod.echo "hello world")' > main.ml
$ ocamlopt -o main mymod.cmx main.ml
$ ./main
saw hello world

OCaml手冊的第2.5節對此進行了描述。

mymod.ml中而不是mymod.mli編寫代碼。 *.ml用於代碼, *.mli用於接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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