package containers

  1. Overview
  2. Docs

Simple and efficient S-expression parsing/printing

  • since 0.4
type 'a or_error = [
  1. | `Ok of 'a
  2. | `Error of string
]
type 'a sequence = ('a -> unit) -> unit
type 'a gen = unit -> 'a option

Basics

type t = [
  1. | `Atom of string
  2. | `List of t list
]
val equal : t -> t -> bool
val compare : t -> t -> int
val hash : t -> int
val atom : string -> t

Build an atom directly from a string

val of_int : int -> t
val of_bool : bool -> t
val of_list : t list -> t
val of_rev_list : t list -> t

Reverse the list

val of_float : float -> t

Reverse the list

val of_unit : t
val of_pair : (t * t) -> t
val of_triple : (t * t * t) -> t
val of_quad : (t * t * t * t) -> t
val of_variant : string -> t list -> t

of_variant name args is used to encode algebraic variants into a S-expr. For instance of_variant "some" [of_int 1] represents the value Some 1

val of_field : string -> t -> t

Used to represent one record field

val of_record : (string * t) list -> t

Represent a record by its named fields

Serialization (encoding)

val to_buf : Buffer.t -> t -> unit
val to_string : t -> string
val to_file : string -> t -> unit
val to_file_seq : string -> t sequence -> unit

Print the given sequence of expressions to a file

val to_chan : Pervasives.out_channel -> t -> unit
val print : Format.formatter -> t -> unit

Pretty-printer nice on human eyes (including indentation)

val print_noindent : Format.formatter -> t -> unit

Raw, direct printing as compact as possible

Deserialization (decoding)

type 'a parse_result = [
  1. | 'a or_error
  2. | `End
]
type 'a partial_result = [
  1. | 'a parse_result
  2. | `Await
]
module Source : sig ... end
module Lexer : sig ... end
module ParseGen : sig ... end
Stream Parser

Returns a lazy stream of S-expressions.

val parse_string : string -> t ParseGen.t

Parse a string

val parse_chan : ?bufsize:int -> Pervasives.in_channel -> t ParseGen.t

Parse a channel

val parse_gen : string gen -> t ParseGen.t

Parse chunks of string

Blocking API

Parse one S-expression from some source.

Parse a S-expression from the given channel. Can read more data than necessary, so don't use this if you need finer-grained control (e.g. to read something else after the S-exp)

val of_string : string -> t or_error
val of_file : string -> t or_error

Open the file and read a S-exp from it

Lists of S-exps
module L : sig ... end
Traversal of S-exp

Example: serializing 2D points

type pt = {x:int; y:int };;

let pt_of_sexp e =
  Sexp.Traverse.(
    field "x" to_int e >>= fun x ->
    field "y" to_int e >>= fun y ->
    return {x;y}
  );;

let sexp_of_pt pt = Sexp.(of_record ["x", of_int pt.x; "y", of_int pt.y]);;

let l = [{x=1;y=1}; {x=2;y=10}];;

let sexp = Sexp.(of_list (List.map sexp_of_pt l));;

Sexp.Traverse.list_all pt_of_sexp sexp;;
module Traverse : sig ... end
OCaml

Innovation. Community. Security.