可选参数的本地抽象类型和默认值

Locally abstract types and default values for optional arguments

我正在为具有两种可能内部格式的矩阵类型编写接口。这是一个简化版本:

type csc (* compressed-sparse-column format *)
type csr (* compressed-sparse-row format *)

type _ fmt =
| CSC : csc fmt
| CSR : csr fmt

type 's matrix = { sparsetype : 's fmt }

let newmat (type s) ?(fmt : s fmt = CSC) () = { sparsetype = fmt }

这不起作用,因为默认值 CSC 不是 s fmt 类型。

看来这个想法是行不通的,因为无法在签名中为类型变量指定默认值,即签名

val newmat : ?(fmt:'s sformat) -> unit -> 's matrix

在未明确指定 fmt 时需要指定 's = csc

有没有办法绕过这个限制?

期望 OCaml 接受这样的定义是不合理的吗?

想要这个不是没有道理的(我自己在很多场合都想要它),但 OCaml 不接受它,并且有充分的理由。它是 在存在的情况下很难与推理相结合 高阶函数。

所以,恐怕你将不得不坚持 non-optional 论点,或者 几个功能。