Skip to content

Instantly share code, notes, and snippets.

@aconz2
Created October 1, 2015 17:32
Show Gist options
  • Save aconz2/37fc04b5f34d215bad54 to your computer and use it in GitHub Desktop.
Save aconz2/37fc04b5f34d215bad54 to your computer and use it in GitHub Desktop.
trying to write polymorphic type generators in ocaml
type exp =
| Int of int
| Succ of exp
| Plus of exp * exp
(* realistically we would want to specify depth and/or the bias of
choosing a certain expression *)
let rec gen_exp () : exp =
match Random.int 3 with
| 0 -> Int (Random.int 42)
| 1 -> Succ (gen_exp ())
| 2 -> Plus (gen_exp (), gen_exp ())
| _ -> raise (Failure "ocaml again doesn't know whats going on")
(* but we'd like to write a polymorphic function *)
let rec gen_typ (typs : ((unit -> 'a) -> 'a) list) : 'a =
let n = Random.int (List.length typs) in
let g = List.nth typs n in
(g (fun () -> gen_typ typs))
(* and we can create a generator like this *)
let gen_exp = fun () -> gen_typ [(fun _ -> Int (Random.int 42));
(fun g -> Succ (g ()));
(fun g -> Plus (g (), g()))]
(* but then we have to write a list of generators every time we have a new type *)
(* Some something like this would be nice (totally made up) *)
(* let rec gen_typ () : 'a = *)
(* let typ = Typ.nth 'a (Random.int (Typ.size 'a)) in *)
(* Typ.create typ (List.map gen_typ (Typ.members typ)) *)
(* but we can't do this because types aren't values *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment