« Return to Thread: "ocaml_beginners"::[] De-unifying variant types

"ocaml_beginners"::[] Re: De-unifying variant types

by cultural_sublimation :: Rate this Message:

Reply to Author | View in Thread

Hi Jon (and other readers),

Thanks for the reply.  Your suggestions did clean up the code quite a
lot, though I am afraid the crux of the matter still remains.  I may be
missing something really important here, but I still cannot find a way
to share the "process_query" function without first creating a variant
type unifying actors and movies, though the code is *exactly* the same
for both types.  Here's the new version, non-working because it lacks
the variant type:

module Actor = struct
  type t = {name: string; age:integer}

  let create = function
    | [|name; age|] -> {name = name; age = int_of_string age}
    | _             -> invalid_arg "Actor.create"
end

module Movie = ... (* similar to Actor, just with the fields changed. *)

type

let process_query query create_fun =
  let result = conn#exec ~expect:[Tuples_ok] query in
  Array.map create_fun result#get_all

let get_actors () =
  let query = "SELECT * from actors" in
  process_query query Actor.create

let get_movies () =
  let query = "SELECT * from movies" in
  process_query query Movie.create


Now, as William D. Neumannn mentioned, there may be no solution to this
problem in Ocaml.  I will have to create a variant type, and then use
a specially crafted function such as the one bellow to extract only
the variant I am interested in:

let refine_movie = function Movie m -> m | _ -> assert false;;

Or is there a more elegant way?

Again, thanks in advance!
Cheers,
C.S.


 « Return to Thread: "ocaml_beginners"::[] De-unifying variant types