Typegist represents the essence of OCaml types as values.
This dynamic type representation can be used to devise generic type-indexed functions – value serializers, generators, differs, editors, FFI glue, etc. Any accessible type can be described up to the limits defined by its public interface.
Typegist does not model OCaml's type language in full detail. It focuses on a core structural subset decorated with typed-indexed metadata to provide an ergonomic interface for both producers and processors of the representation.
The following manuals are available:
typegistTypegist Extended Stdlib.Type and Stdlib.Fun modules. Open to use it.Typegist.Type.Gist Type gists.Typegist.Fun.Generic Generic functions.The following shows how to define type gists for a simple data model for todo items. Among other Typegist.Fun.Generic functions this immediately gives us pretty-printing and random generation for testing. Other libraries may give you more, for example the jsont.typegist library derives JSON types from a type gists and thus provides JSON serialization out of the box for the data model.
open Typegist
module Status = struct
type t = Todo | Done | Cancelled
let enum = ["Todo", Todo; "Done", Done; "Cancelled", Cancelled ]
let gist = Type.Gist.variant_of_enum ~name:"Status.t" enum
let pp = Fun.Generic.pp gist
end
module Item = struct
type t = { task : string; status : Status.t; tags : string list }
let make task status tags = { task; status; tags }
let task i = i.task
let status i = i.status
let tags i = i.tags
let gist =
Type.Gist.record "Item.t" make
|> Type.Gist.field "task" Type.Gist.utf_8_string task
|> Type.Gist.field "status" Status.gist status
|> Type.Gist.field "tags" Type.Gist.(list utf_8_string) tags
|> Type.Gist.finish
let pp = Fun.Generic.pp gist
end
type items = Item.t list
let items_gist = Type.Gist.list ~name:"items" Item.gist
let random_items = Fun.Generic.random items_gist ()If you find the randomness to be too arbitrary it is possible to influence the generation process by adding metadata to the description, see this cookbook entry.
The cookbook has more type gist modelling blueprints.