Mik*_*uel 5 ocaml abbreviation
我有两个模块.一个定义变体类型:
module A = struct
type foo = Bar of material | Baz | Boo
(* other stuff *)
end
Run Code Online (Sandbox Code Playgroud)
我希望能够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
Run Code Online (Sandbox Code Playgroud)
但是对于"引用命名对象",我必须在变量名称前加上一个模块路径:
let f (x : foo) = match x with
| A.Bar m -> A.Bar (g m)
| A.Baz | A.Boo -> x
Run Code Online (Sandbox Code Playgroud)
是否有任何方法可以避免使用模块路径,open而不是将所有其他内容从中拉出来A?
您可以在本地打开A:
let f (x : foo) = A.(match x with
| Bar m -> Bar (g m)
| Baz | Boo -> x)
Run Code Online (Sandbox Code Playgroud)
要么
let f (x : foo) =
let open A in
match x with
| Bar m -> Bar (g m)
| Baz | Boo -> x)
Run Code Online (Sandbox Code Playgroud)
您可以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
...
Run Code Online (Sandbox Code Playgroud)
要在模式之外使用,可以在B中定义"智能构造函数":
let bar m = A.Bar m
Run Code Online (Sandbox Code Playgroud)
ETA:我忘记了重述类型定义的可能性,在Ashish Argwal的回答中描述:type foo = A.foo = Bar of material | Baz | Boo.鉴于您的示例中已经有类型缩写,这是最好的答案.
有一些关于基于类型的标签消歧的工作可能会有所帮助,但它可能无法被语言接受.