module - OCaml 模块 : include AND open?

标签 module ocaml

我对 OCaml 模块还很陌生,如果不结合“包含”和“打开”,我就无法使用自己的模块。
我试图将签名放在单独的 .mli 文件中,但没有成功。

下面我指出了一个最小(非)工作示例,我正在尝试使用它进行编译

ocamlc -o main Robot.ml main.ml

我需要做什么才能只使用“open”,或者只使用“include”,但不能同时使用它们?

文件“Robot.ml”:
module type RobotSignature =
sig 
   val top: unit -> unit
end

module Robot =
struct
   let top () = 
      begin
         Printf.printf "top\n"
      end
   (* Should not be visible from the 'main' *)
   let dummy () = 
      begin
         Printf.printf "dummy\n"
      end
end

文件“main.ml”(不工作):
open Robot;;

top();

文件“main.ml”(工作):
include Robot;;
open Robot;;

top();

最佳答案

你有两个级别的机器人。由于您在文件 robot.ml 中明确调用了模块“Robot”,因此您需要打开 Robot,然后调用 Robot.top()。 robots.ml 文件中的任何内容都已隐式放入 Robot 模块中。

您可以去掉 robots.ml 中额外的“模块机器人”声明。

robots.ml 将变为:

module type RobotSignature =
sig 
   val top: unit -> unit
end


let top () = 
   begin
       Printf.printf "top\n"
   end

然后它应该像你在 main.ml 中那样工作。

根据以下评论进行更新:如果您担心“打开机器人”时 robots.ml 中的所有内容现在都可见,您可以定义一个 robots.mli 文件,该文件指定外部可用的功能。例如,假设您添加了一个名为 的函数。 helper 在机器人.ml 中:
let top () =
  begin
     Printf.printf "top\n"
  end

let helper () =
  Printf.printf "helper\n"

...然后你定义你的robot.mli如下:
val top: unit -> unit

然后假设您尝试从 main.ml 调用 helper:
open Robot;;

top();
(* helper will not be visible here and you'll get a compile error*)
helper ()

然后当你尝试编译时,你会得到一个错误:
$ ocamlc -o main robot.mli robot.ml main.ml
File "main.ml", line 4, characters 0-6:
Error: Unbound value helper

关于module - OCaml 模块 : include AND open?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9997822/

相关文章:

javascript - 有没有办法使用 EXPORT * 导出 ES6 模块中的所有名称?

python - Blender Python `bpy` `__init__.py` ,显然是从不存在的模块 `_bpy` 导入的

Angular 动态模块提供者

recursion - 扩展相互递归的仿函数

string - OCaml 测试字符串是否几乎为空或包含关键字

multithreading - 如何在 OCaml 中使用线程模块

python - 导入 pbnt (贝叶斯网络模块)并获取 AttributeError

module - 如何组织 Lua 模块路径并编写 "require"调用而不失去灵活性?

algorithm - 创建快速指数函数

functional-programming - OCaml 中的弱多态性