Version française
Home     About     Download     Resources     Contact us    
Browse thread
ANN: Sexplib - library for S-expression conversions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: N. Owen Gunden <ogunden@p...>
Subject: Re: [Caml-list] ANN: Sexplib - library for S-expression conversions
On Mon, Nov 07, 2005 at 06:09:34PM -0500, Markus Mottl wrote:
> we'd like to announce the availability of "Sexplib" [...]

And here are some simple usage examples:

----------------
# open Sexplib;;

# type t = { foo : int; bar : string; } with sexp;;
type t = { foo : int; bar : string; }
val sexp_of_t : t -> Sexplib.Sexp.t = <fun>
val t_of_sexp : Sexplib.Sexp.t -> t = <fun>

# let v = { foo = 3; bar = "baz"; };;
val v : t = {foo = 3; bar = "baz"}

# sexp_of_t v;;
- : Sexplib.Sexp.t = ((foo 3) (bar baz))

# t_of_sexp (Sexp.of_string "((foo 31337) (bar \"quux\"))");;
- : t = {foo = 31337; bar = "quux"}
----------------

You can also just get a converter for a specific direction, not both:

----------------
# type foo = A | B with sexp_of;;
type foo = A | B
val sexp_of_foo : foo -> Sexplib.Sexp.t = <fun>

# type foo = A | B with of_sexp;;
type foo = A | B
val foo_of_sexp : Sexplib.Sexp.t -> foo = <fun>
----------------

A more complicated example, building a bigger type out of the same t we
used above:

----------------
# type t' = t * [`foo|`bar] with sexp_of;;
type t' = t * [ `bar | `foo ]
val sexp_of_t' : t * [< `bar | `foo ] -> Sexplib.Sexp.t = <fun>

# sexp_of_t' (v, `foo);;
- : Sexplib.Sexp.t = (((foo 3) (bar baz)) foo)
----------------

I can also manually define the converter for a type that's contained
within, and the converter for the larger type will use mine:

----------------
# let sexp_of_t t = Sexp.Atom (Printf.sprintf "<t with foo=%d and bar=%S>" t.foo t.bar);;
val sexp_of_t : t -> Sexplib.Sexp.t = <fun>

# type t' = t * [`foo|`bar] with sexp_of;;
type t' = t * [ `bar | `foo ]

val sexp_of_t' : t * [< `bar | `foo ] -> Sexplib.Sexp.t = <fun>
# sexp_of_t' (v, `foo);;
- : Sexplib.Sexp.t = ("<t with foo=3 and bar=\"baz\">" foo)
----------------

 - O