在Ocaml中缩写构造函数名称 [英] Abbreviating constructor names in Ocaml

查看:76
本文介绍了在Ocaml中缩写构造函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模块.一个定义了一个变体类型:

I have two modules. One defines a variant type:

module A = struct
  type foo = Bar of material | Baz | Boo

  (* other stuff *)
end

,我希望能够将foo的变体既用作构造函数,又用作另一个模块的左侧

and I would like to be able to use foo's variants both as constructors and as left-hand-sides in another module

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

但根据引用命名对象" 我必须在变体名称前加上 module-path :

but per "referring to named objects" I have to prefix the variant names with a module-path:

  let f (x : foo) = match x with
    | A.Bar m         -> A.Bar (g m)
    | A.Baz   | A.Boo -> x

有什么方法可以跳过,避免使用缺少open的模块路径,并从A中提取所有其他内容?

Is there any way to skip avoid using the module path short of opening and pulling in all the other stuff from 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,以便暴露更少的内容:

You can define Bar in a submodule so that less things are exposed:

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中定义一个智能构造函数":

For use outside of patterns, you can define a "smart constructor" in B:

let bar m = A.Bar m

ETA:我忘记了重新声明类型定义的可能性,这在Ashish Argwal的答案type foo = A.foo = Bar of material | Baz | Boo中有所描述.鉴于您的示例中已经输入了缩写,这是最好的答案.

ETA: I forgot about the possibility to restate type definition, described in Ashish Argwal's answer: type foo = A.foo = Bar of material | Baz | Boo. Given that you already have type abbreviation in your example, this is the best answer.

关于基于类型的标签消除歧义这可能会有所帮助,但可能不会被该语言接受.

There is some work on type-based label disambiguation which could be helpful, but it may not get accepted into the language.

这篇关于在Ocaml中缩写构造函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆