【问题标题】:What's "parenthesis type" as in (type v) in a definition or in a function signature?定义或函数签名中的 (type v) 中的“括号类型”是什么?
【发布时间】:2023-01-28 18:11:18
【问题描述】:

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

【问题讨论】:

  • 看看您是否可以在手册的 GADT 部分找到有用的内容。

标签: generics types ocaml


【解决方案1】:

它们是局部抽象类型。见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

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 2012-09-14
    • 2019-11-29
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2014-05-30
    相关资源
    最近更新 更多