added a conversion example: Json (with yojson type)

This commit is contained in:
Simon Cruanes 2014-02-27 00:45:23 +01:00
parent 898d2c0492
commit a523c63c7f
2 changed files with 64 additions and 0 deletions

41
conv.ml
View file

@ -351,6 +351,46 @@ let rec into : type a b. a Source.t -> b Sink.universal -> a -> b =
let from (src:'a Source.universal) (sink:'b Sink.t) (x:'a) : 'b = src#visit sink x
(** {6 Exemples} *)
module Json = struct
type t = [
| `Int of int
| `Float of float
| `Bool of bool
| `Null
| `String of string
| `List of t list
| `Assoc of (string * t) list
]
let source = object(self)
inherit [t] Source.universal
method visit sink (x:t) = match x with
| `Int i -> self#int_ sink i
| `Float f -> self#float_ sink f
| `Bool b -> self#bool_ sink b
| `Null -> self#unit_ sink
| `String s -> self#string_ sink s
| `List l -> self#list_ sink l
| `Assoc l -> self#record sink l
end
let sink : t Sink.universal = object
method unit_ = `Null
method bool_ b = `Bool b
method float_ f = `Float f
method int_ i = `Int i
method string_ s = `String s
method list_ l = `List l
method record l = `Assoc l
method tuple l = `List l
method sum name l = match l with
| [] -> `String name
| _::_ -> `List (`String name :: l)
end
end
(* test for records *)
type point = {
@ -378,4 +418,5 @@ let point_source : point Source.t =
let p = {x=1; y=42; color="yellow"; }
let p2 = into point_source Json.sink p
(* TODO tests *)

View file

@ -28,6 +28,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
exception ConversionFailure of string
(** {6 Sinks}
A sink is used to traverse values of some type 'a *)
module Sink : sig
(** A specific sink that requires a given shape to produce
* a value of type 'a *)
@ -94,6 +96,8 @@ module Sink : sig
end
end
(** {6 Sources}
A source is used to build values of some type 'a *)
module Source : sig
(** A specific source that follows the shape of the type 'a *)
type 'a t =
@ -166,8 +170,27 @@ module Source : sig
end
end
(** {6 Conversion Functions} *)
val into : 'a Source.t -> 'b Sink.universal -> 'a -> 'b
(** Conversion to universal sink *)
val from : 'a Source.universal -> 'b Sink.t -> 'a -> 'b
(** Conversion from universal source *)
(** {6 Exemples} *)
module Json : sig
type t = [
| `Int of int
| `Float of float
| `Bool of bool
| `Null
| `String of string
| `List of t list
| `Assoc of (string * t) list
]
val source : t Source.universal
val sink : t Sink.universal
end