Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
type _ ty = Int_t : int ty | List_t : 'a ty -> 'a list ty
type ex_ty = Ex_ty : _ ty -> ex_ty
type ex_value = Ex_value : 'a ty * 'a -> ex_value
let rec encode_ty : type a. a ty -> string = function
| Int_t -> "Int_t"
| List_t ty -> Format.sprintf "List_t(%s)" (encode_ty ty)
let rec decode_ty : type a. string -> ex_ty =
fun string ->
let name, content =
match String.index_opt string '(' with
| Some start ->
( String.sub string 0 start,
String.sub string start (String.length string - 1) )
| None -> (string, "")
in
match name with
| "Int_t" -> Ex_ty Int_t
| "List_t" ->
let (Ex_ty ty) = decode_ty content in
Ex_ty (List_t ty)
| _ -> raise (Invalid_argument "unknown ty")
let rec encode : type a. a ty -> a -> string =
fun (type a) (ty : a ty) (v : a) ->
( let value =
match ty with
| Int_t -> Format.sprintf "%d" v
| List_t ty -> v |> List.map (encode ty) |> String.concat ";"
in
Format.sprintf "%s %s" (encode_ty ty) value
: string )
let rec decode_value : type a. a ty -> string -> a =
fun (type a) (ty : a ty) string ->
( match (ty, string) with
| Int_t, int -> int_of_string int
| List_t ty, values ->
let values = String.split_on_char ';' values in
values |> List.map (decode_value ty)
: a )
let decode : type a. string -> ex_value =
fun string ->
let ty, value =
match String.split_on_char ' ' string with
| [ ty; value ] -> (ty, value)
| _ -> raise (Invalid_argument "unknown format")
in
let (Ex_ty ty) = decode_ty ty in
let value = decode_value ty value in
Ex_value (ty, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment