原因模块系统

5

https://facebook.github.io/reason/modules.html#modules-basic-modules

I don’t see any import or require in my file; how does module resolution work?

Reason/OCaml doesn’t require you to write any import; modules being referred to in the file are automatically searched in the project. Specifically, a module Hello asks the compiler to look for the file hello.re or hello.ml (and their corresponding interface file, hello.rei or hello.mli, if available).
A module name is the file name, capitalized. It has to be unique per project; this abstracts away the file system and allows you to move files around without changing code.

我尝试了 Reason 模块系统,但无法理解其工作原理。

1) openinclude 有什么区别?

2) 我有一个定义了模块 Foo 的文件 foo.re,我有另一个文件 bar.re,想要调用 Foo 模块中的函数。

bar.re 中,我应该 open 还是 include Foo 模块?还是直接访问 - Foo.someFunction

3) 模块接口只能在 *.rei 文件中实现吗?并且模块接口文件应该与同名但扩展名为 rei 的文件相同吗?

1个回答

11

1) open 就像 import 一样,它将导出的定义添加到本地命名空间。而 include 则像从被包含模块复制定义到被包含者一样将它们添加到模块中。ìnclude 因此也会导出这些定义(除非有一个接口文件 / 签名限制导出的内容)。

2) 为了不必要地污染命名空间,你应该优先考虑最本地的模块使用。因此,通常你需要使用直接访问,只有当一个模块特别设计成在文件级别上打开时才应该这样做。然而,还有一些比文件级别更本地的 open 形式。你可以仅在函数范围内或者仅在单个表达式作用域内使用 open,例如 Foo.(someFunction 4 |> otherFunction 2)

3) 顶层(文件)模块必须以与 re 文件相同的名称形式实现一个 rei 文件。但是你可以为子模块定义模块类型作为“接口”。

OCaml 的模块系统相当广泛和灵活。我建议阅读 Real World Ocaml 的模块章节以更好地掌握它:https://realworldocaml.org/v1/en/html/files-modules-and-programs.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接