ocamlgadtlocally-abstract-type

Locally abstract types and default values for optional arguments


I am writing an interface for a matrix type with two possible internal formats. Here is a simplified version:

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 }

This does not work since the default value CSC is not of type s fmt.

It seems that this idea has no chance of working, since it is not possible to specify default values for type variables in signatures, that is, the signature

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

would somehow need to specify that 's = csc when fmt is not explicitly specified.

Is there a way around this limitation?

Is it unreasonable to expect OCaml to accept such definitions?


Solution

  • It isn't unreasonable to want this (and I wanted it on many occasions myself), but OCaml doesn't accept it, and for rather good reasons. It's pretty difficult to combine with inference in the presence of high order functions.

    So, I'm afraid you will have to stick to non-optional arguments, or make several functions.