OCaml:如何获取 mli 文件本地的模块别名

问题描述 投票:0回答:3

是否可以在 mli 中为模块添加别名而不创建“必须实现的新模块”。 这个示例非常人为,但是,例如,假设我有以下源文件 int_wrapper.ml。

type t = Int64.t

let zero = Int64.of_string "0"

我想为它定义一个接口文件,但是 Int64.t 太长了,所以我想缩写它。

module I = Int64

val zero : int -> I.t

尝试编译模块时,我(可以预见)收到以下错误

ocamlbuild int_wrapper.cmo
+ ~/.opam/4.03.0/bin/ocamlc.opt -c -o int_wrapper.cmo int_wrapper.ml
File "int_wrapper.ml", line 1:
Error: The implementation int_wrapper.ml
   does not match the interface int_wrapper.cmi:
   The module `I' is required but not provided
Command exited with code 2.
Compilation unsuccessful after building 4 targets (0 cached) in 00:00:00.
Exit 10

那是因为

module I = Int64
不是别名。我实际上正在定义一个与
Int64
相同的新模块,并且由于该模块位于签名中,因此我需要在源文件中提供实现。 有没有办法在接口文件中获取真正的别名?

ocaml
3个回答
6
投票

从 OCaml 4.08 开始(请参阅发行说明),现在可以通过 本地替换声明:

module I := Int64

3
投票

模块别名需要出现在

.ml
.mli
文件中,因为它们被导出。您可以通过将它们放入您使用
open
的单独文件中来解决此问题,例如:

==> abbrevs.ml <==
module I = Int64

==> int_wrapper.ml <==
type t = Int64.t

let zero = Int64.of_string "0"

==> int_wrapper.mli <==
open Abbrevs
val zero : I.t

2
投票

无法在 .mli 文件中包含供本地使用的模块同义词(据我通过查看 OCaml 语法定义可知)。

如果您愿意在 .ml 文件和 .mli 文件中定义

I
,那么 .ml 文件将提供正确的接口。

$ cat a.ml
module I = Int64
type t = I.t
let zero = I.of_string "0"
$ cat a.mli
module I = Int64
type t = I.t
val zero : I.t
$ ocamlc -c a.mli a.ml
© www.soinside.com 2019 - 2024. All rights reserved.