Ocaml通过它们与值的接近程度消除推断类型的歧义?

时间:2017-03-13 05:15:08

标签: ocaml type-inference algebraic-data-types subtyping refinement-type

type large1 = Int of int | Bool of bool
type small1 = Int of int    
let intersect1 = Int 0

ocaml top-level(4.01.0)将intersect1的类型推断为small1。我以为我明白了原因:small1看起来像large1的子类型(或细化类型)。

但现在:

type small2 = Int of int
type large2 = Int of int | Bool of bool    
let intersect2 = Int 0

现在,顶级会为large2推断出intersect2的类型。这使得看起来邻近被用作决胜局,但这非常令人惊讶,并且与我使用的其他语言不同,所以我怀疑这里存在一些微妙的误解。

一个复杂因素:如the question that inspired the answer that inspired this question所述,“更接近”类型并不能完全隐藏另一个类型。

type left = Int of int | Dem
type right = Int of int | Gop

let zell (x:left) =
  match x with
    Int v -> Int v
  | Dem -> Gop

zell的类型为left -> right

推断这些类型的具体规则是什么?我可以在manual(或任何其他已发表的论文或文档)中阅读更多内容?

This question was inspired by an older answer to a question about polymorphic variants.

1 个答案:

答案 0 :(得分:2)

OCaml有"类型导向"这几天记录领域和建设者的消歧。

它已添加到2012年9月12日发布的OCaml 4.01.0的语言中。发行说明参考此链接以获取更多信息:

Type-based selection of record labels and constructors.

这是一篇很好的文章,描述了进行变革的思维过程:

Resolving Field Names

以下是更多细节的跟进:

Resolving Field Names 2

我无法找到OCaml手册中提到的此功能(正如您所说)。