samoht / depyt

Yet another type combinator library
https://samoht.github.io/depyt/doc/Depyt.html
ISC License
54 stars 9 forks source link

Depyt — yet-an-other type combinator library

Depyt provides type combinators to define runtime representation for OCaml types and generic operations to manipulate values with a runtime type representation.

The type combinators supports all the usual type primitives but also compact definitions of records and variants. It also allows to define the runtime representation of recursive types.

Depyt is a modern reboot of Dyntype but using GADTs-based combinators instead of syntax-extensions. When we originally wrote Dyntype (in 2012) GADTs were not available in OCaml and camlp4 was everywhere -- this is not the case anymore. Finally, Depyt avoids some of the performance caveats present in Dyntype by avoiding allocating and converting between intermediate formats.

Variants

For instance, to define variants:

# #require "depyt";;
# open Depyt;;
# type t = Foo | Bar of string option;;
type t = Foo | Bar of string option
# let t =
    variant "v" (fun foo bar -> function Foo -> foo | Bar x -> bar x)
    |~ case0 "Foo" Foo
    |~ case1 "Bar" (option string) (fun x -> Bar x)
    |> sealv
    ;;
val t : t Depyt.t = <abstr>
# Fmt.pr "t = %a\n%!" (dump t) Foo;;
t = Foo
- : unit = ()
# compare t Foo (Bar (Some "a"));;
- : int = -1
# compare t Foo (Bar (Some "a"));;
- : int = -1

Records

To define records:

# type t = { foo: int option; bar: string list };;
type t = { foo : int option; bar : string list; }
# let t =
    record "r" (fun foo bar -> { foo; bar })
    |+ field "foo" (option int) (fun t -> t.foo)
    |+ field "bar" (list string) (fun t -> t.bar)
    |> sealr
    ;;
val t : t Depyt.t = <abstr>
# Fmt.pr "%a\n%!" (dump t) { foo = Some 3; bar = ["foo"] };;
{ foo = Some 3; bar = ["foo"]; }
- : unit = ()
# (* [None] fields do not appear in the generated JSON *)
# Fmt.pr "%a\n%!" (pp_json t) { foo = None; bar = ["1";"2"] };;
{"bar":["1","2"]}
- : unit = ()

Depyt is distributed under the ISC license.

Homepage: https://github.com/samoht/depyt

Installation

Depyt can be installed with opam:

opam install depyt

If you don't use opam consult the opam file for build instructions.

Documentation

The documentation and API reference is automatically generated by from the source interfaces. It can be consulted online or via odig doc depyt.