在OCaml中键入构造函数别名而不"污染"模块

ano*_*nol 6 ocaml types module

我想为在给定模块中重用的构造函数定义一个类型别名,而不必通过它们定义它们的模块的路径作为前缀.我还想通过执行导入太多定义的open/ 来避免"污染"后一个模块include.

这是我想要的一个例子(不编译):

module A = struct
  type t = Red | Blue
end

module B = struct
  type t = A.t
  let f = function
    | Red -> 1  (*Error: Unbound constructor Red*)
    | Blue -> 0
  let
end
Run Code Online (Sandbox Code Playgroud)

这样做include Aopen A内B将都在这里工作(RedBlue将是有效的),但都将增加定义,B,"污染"了.

open将造成最小的伤害,但仍然允许犯错误,例如,如果A定义了B由于意外使用的符号open,我将不会有编译错误.

有没有办法避免这种"污染",同时阻止我输入A.Red/ A.Blue在模块B中?

Pat*_*atJ 8

就在这里.

在定义tB,您可以声明它等于A.t并重写其构造函数的列表:

module B = struct
  type t = A.t = Red | Blue
  let f = function
    | Red -> 1
    | Blue -> 0
end
Run Code Online (Sandbox Code Playgroud)

类型检查器将验证定义是否完全相同,A即使您在A中修改类型定义,也会提醒您更改它B(是的,您键入两次相同的东西,但它是一个简单的哑副本/糊).

  • 不要犹豫检查OCaml手册,第二部分起初有点可怕,但包含非常有趣和有用的信息. (2认同)