Search code examples
ocamlocaml-core

OCaml: Core.Univ usage example


So I have been looking at Core.Univ as a way of constructing heterogeneous arrays.

Suppose I do

let int_type = Core.Type_equal.Id.create ~name:"" Sexplib.Conv.sexp_of_int;;
let int_type' = Core.Type_equal.Id.create ~name:"" Sexplib.Conv.sexp_of_int;;

let i = Core_kernel.Univ.create int_type 5;;
let j = Core_kernel.Univ.create int_type' 5;;

When I do

Core_kernel.Univ.match_ i int_type'

It doesn't match as expected since the documentation for Type_equal.Id says that two calls to create with the exact same arguments will result in two distinct identifiers.

Does this mean that the API user is responsible for ensuring that only one instance of Type_equal.Id exists for each type?


Solution

  • Yes. I'd say that Core's terminology is a little bit unfortunate here.

    Remember that once you compiled your program, at runtime there are (almost) no types in OCaml (see e.g. here or here for more information).

    This means there's no way to introspect the values returned by Core.Type_equal.Id.create to detect for which type they really are and hence no way to detect if you already invoked create for an existing identical type (which would allow to return an already created identifier).

    Rather than identifiers for types you should rather see these values as typed key identifiers. By controlling who has access to these key identifiers trough the module system you can control in a type safe way who can access the contents of universal values that were created with them.