OCaml Code Generation

paradox generate --ocaml [--path PATH]

Product Types

Input:

type Person
  name: Text
  age: Integer
  admin: Boolean

Output:

type person =
{ name : string
; age : int
; admin : bool
}

Type names are lowercased per OCaml convention.

JSON Serialization

Uses Yojson:

let person_to_yojson (x : person) : Yojson.Safe.t =
  `Assoc [
    ("name", `String x.name);
    ("age", `Int x.age);
    ("admin", `Bool x.admin)
  ]

let person_of_yojson (json : Yojson.Safe.t) : (person, string) result =
  match json with
  | `Assoc fields ->
    (try Ok {
      name = (match List.assoc "name" fields with `String s -> s | _ -> failwith "expected string");
      age = (match List.assoc "age" fields with `Int i -> i | _ -> failwith "expected int");
      admin = (match List.assoc "admin" fields with `Bool b -> b | _ -> failwith "expected bool");
    }
    with Failure msg -> Error msg)
  | _ -> Error "expected JSON object for Person"

Validators

let valid_person (x : person) : (person, string) result =
  let errors = ref [] in
  if !errors = [] then Ok x
  else Error (String.concat "; " (List.rev !errors))

let is_valid_person (x : person) : bool =
  match valid_person x with Ok _ -> true | Error _ -> false

Union Types

Unions become OCaml variant types with polymorphic variant JSON encoding.