记录标签必须全球唯一吗?

Nic*_*ner 3 ocaml

可能重复:
两个记录中的两个字段在OCaml中具有相同的标签

在Ocaml 3.12.0中,记录的任何标签是否必须具有全局唯一名称?

type foo = { a : int; b : char; }
# type bar = {a : int; b : string};;
type bar = { a : int; b : string; }
# {a=3; b='a'};;
  {a=3; b='a'};;
Error: This expression has type char but an expression was expected of type
         string
Run Code Online (Sandbox Code Playgroud)

我想如果记录是匿名创建的,那么编译器知道我所指的是哪种类型的记录名称的唯一方法.声明bar隐藏foo吗?

pad*_*pad 7

不,记录标签不必是全局唯一的.但它们必须在模块级别上是独一无二的.

声明bar不隐藏foo; 因此,在引用b字段时类型推断被破坏.

您可以轻松创建子模块并使用模块名称来区分具有相同标签的记录:

module Foo = struct
  type foo = {a: int; b: char}
end

module Bar = struct
  type bar = {a: int; b: string}
end

let f = {Foo.a = 3; b = 'a'} (* Note that we only need to use module name once *)
let b = {Bar.a = 3; b = "a"}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用Foo.(...)形式的本地模块打开.在尝试限制open的范围时,此语法很有用. (3认同)