我有两个模块。一个定义了一个变体类型:
module A = struct
type foo = Bar of material | Baz | Boo
(* other stuff *)
end
我希望能够使用
foo
的变体既作为构造函数又作为另一个模块中的左侧module B = struct
type foo = A.foo (* I can abbreviate A.foo by assigning it a local alias *)
let f (x : foo) = match x with
| Bar m -> Bar (g m) (* Any way to abbreviate Bar and friends? *)
| Baz | Boo -> x
end
但根据 "referring to named objects"我必须在变体名称前面加上一个模块路径:
let f (x : foo) = match x with
| A.Bar m -> A.Bar (g m)
| A.Baz | A.Boo -> x
有什么方法可以跳过避免使用
open
的模块路径短从 A
中提取和提取所有其他内容?
最佳答案
您可以在本地打开A:
let f (x : foo) = A.(match x with
| Bar m -> Bar (g m)
| Baz | Boo -> x)
或者
let f (x : foo) =
let open A in
match x with
| Bar m -> Bar (g m)
| Baz | Boo -> x)
您可以定义
Bar
在子模块中,以便暴露更少的东西:module A = struct
module BasicDataAndOps = struct
type foo = Bar of material | Baz | Boo
end
open BasicDataAndOps
(* other stuff *)
end
module B = struct
open A.BasicDataAndOps
...
为了在模式之外使用,您可以在 B 中定义一个“智能构造函数”:
let bar m = A.Bar m
ETA:我忘记了重述类型定义的可能性,如 Ashish Argwal 的回答中所述:
type foo = A.foo = Bar of material | Baz | Boo
.鉴于您的示例中已经有类型缩写,这是最好的答案。type-based label disambiguation 上有一些工作这可能会有所帮助,但它可能不会被语言所接受。
关于ocaml - 在 Ocaml 中缩写构造函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13538985/