在 OCaml 中,定义或函数签名中的 (type v) 中的 "parenthesis type" 是什么?

in OCaml, what's "parenthesis type" as in (type v) in a definition or in a function signature?

我知道泛型类型,但有时我会在代码中看到 let a (type v w) etc.,有什么区别?

它们是局部抽象类型。参见 https://ocaml.org/manual/locallyabstract.html。它们适用于:

  • 创建本地模块
let sort_and_deduplicate (type a) compare l =
  let module S = Set.Make(struct type t = a let compare = compare end) in
  S.elements (S.of_list l)
  • 在存在 GADT 的情况下优化模式匹配类型
type _ monoid = Int: int monoid | Float: float monoid
let zero (type a) (m:a monoid): a =  match m with
| Int -> 0
| Float -> 0.
  • 调试多态函数
let wrong_id (type a) (x:a) = x + 1
Error: This expression has type a but an expression was expected of type int