我试图理解的目的局部抽象类型在 OCaml 中。局部抽象类型与类型变量有何不同?看来他们有相同的行为:
(* Type variable *)
# let f (x : 'a) : 'a = x;;
val f : 'a -> 'a = <fun>
(* Locally abstract type *)
# let f (type a) (x : a) : a = x;;
val f : 'a -> 'a = <fun>
统一类型变量和局部抽象类型具有完全不同的行为。
特别是,记住统一类型变量很有用:
let f (x:'a) (y:'a) : 'a = ()
是有效的并且产生f: unit -> unit -> unit
.
let f x =
let () = (():'a) in
(x:'a)
相反,局部抽象类型是:
-
局部抽象,因此它们不能与任何其他类型统一。
例如,
let f (type a) (x:a) (y:a) : a = ()
产生预期的
Error: This expression has type unit but an expression was expected of type a
- 由于范围良好,本地类型的寿命不能超出其范围。
通常,
let f x =
let y (type a): a = assert false
(* let's pretend that we can define such `y` value *) in
(x:a)
产生预期的超出范围的错误
Error: Unbound type constructor a
由于这些根本的行为差异,本地抽象类型已被扩展以支持类型系统的更高级功能。
事实上,局部抽象类型:
- 可用于定义本地模块,因为它们是类型构造函数而不是类型变量
let f (type a) (cmp:a -> a -> int) (x:a list) =
let module S = Set.Make(struct type t = a let compare = cmp end) in
x |> S.of_list |> S.elements
- 在 GADT 上进行模式匹配时,可以使用局部类型方程进行细化,因为它们具有明确定义的范围:
type _ t =
| Int: int t
| Float: float t
let zero (type a) (x:a t) = match x with
| Int -> 0 (* in this branch a = int *)
| Float -> 0. (* whereas a = float in this one*)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)