Ocaml 通过与值的接近程度来消除推断类型的歧义?
Ocaml disambiguates inferred types by their proximity to the value?
type large1 = Int of int | Bool of bool
type small1 = Int of int
let intersect1 = Int 0
ocaml 顶层 (4.01.0) 将 intersect1
的类型推断为 small1
。我想我明白了为什么:small1
看起来像 large1
.
的子类型(或细化类型)
但现在:
type small2 = Int of int
type large2 = Int of int | Bool of bool
let intersect2 = Int 0
顶层现在为 intersect2
推断出 large2
的类型。这使得它看起来像 proximity 被用作决胜局,但这非常令人惊讶并且与我使用的其他语言不同,所以我怀疑我误解了这里的一些微妙之处。
一个并发症:如 the question that inspired the answer that inspired this question 中所述,"closer" 类型并没有完全隐藏另一个。
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.
OCaml 最近对记录字段和构造函数进行了 "type-directed" 消歧。
自 2012 年 9 月 12 日发布的 OCaml 4.01.0 起,它已添加到语言中。发行说明参考此 link 以获取更多信息:
Type-based selection of record labels and constructors.
这里有一篇很好的文章,描述了做出改变的思维过程:
这里是更详细的跟进:
我找不到 OCaml 手册中提到的这个功能(如您所说)。
type large1 = Int of int | Bool of bool
type small1 = Int of int
let intersect1 = Int 0
ocaml 顶层 (4.01.0) 将 intersect1
的类型推断为 small1
。我想我明白了为什么:small1
看起来像 large1
.
但现在:
type small2 = Int of int
type large2 = Int of int | Bool of bool
let intersect2 = Int 0
顶层现在为 intersect2
推断出 large2
的类型。这使得它看起来像 proximity 被用作决胜局,但这非常令人惊讶并且与我使用的其他语言不同,所以我怀疑我误解了这里的一些微妙之处。
一个并发症:如 the question that inspired the answer that inspired this question 中所述,"closer" 类型并没有完全隐藏另一个。
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.
OCaml 最近对记录字段和构造函数进行了 "type-directed" 消歧。
自 2012 年 9 月 12 日发布的 OCaml 4.01.0 起,它已添加到语言中。发行说明参考此 link 以获取更多信息:
Type-based selection of record labels and constructors.
这里有一篇很好的文章,描述了做出改变的思维过程:
这里是更详细的跟进:
我找不到 OCaml 手册中提到的这个功能(如您所说)。