Type level OR
I'm using phantom types to track whether the elements of a sorted list are unique. The signature of the module is as follows:
type nonuniq
type uniq
type elt
type _ t = private elt list
val of_list: elt list -> nonuniq t
val inter: ? t -> ? t -> ? t
val uniq: _ t -> uniq t
...
The problem is how to specify the signature of the intersection. val inter: 'state t -> 'state t -> 'state t is not good enough because an intersection between a list with unique and a list with non-unique elements makes sense and results in a list with unique elements. Basically the return type would need to be a result of a boolean OR function:
uniq -> uniq -> uniq
uniq -> nonuniq -> uniq
nonuniq -> uniq -> uniq
nonuniq -> nonuniq -> nonuniq
An obvious solution is to split the signature into two based on the first argument, however it is not the most elegant:
val inter: uniq t -> _ t -> uniq t
val inter': nonuniq t -> 'state t -> 'state t
I found a potentially better solution that almost works (based on link):
type nonuniq = [`NonUniq]
type uniq = [nonuniq | `Uniq]
type elt
type _ t
val of_list: elt list -> [> nonuniq] t
val inter: 'state t -> 'state t -> 'state t
val uniq: _ t -> uniq t
...
val is_uniq: uniq t -> unit (* for testing *)
val is_nonuniq: nonuniq t -> unit
The problem is however that [> nonuniq] t unifies with uniq t, so is_uniq always type checks (is_nonuniq works as expected, though). Is there a way to write a function that only accepts uniq t (and not [> nonuniq] t)?
Posted Oct 8, 2021, 7:49 PM UTC · edited
A general solution, using GADTs, is to encode the type-level operations as relations through GADT indices, effectively embedding a Prolog-style program in the type declaration. This is not implicit at the usage site: users need to provide a "proof" of the computation.
Thanks, I was actually aware of this approach, but I didn't consider it to be much better than splitting the signature, it's still on the user to choose the right alternative. My other failed attempt was to try to pack the operation with the data, but I couldn't figure out how to combine two of them together (and get a properly polymorphic result). I tryed something like this:
There is no way to make this work, right? I guess considering there are no implicit features in the language, there really is no better way to do this...