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

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

by Jon Harrop :: Rate this Message:

Reply to Author | View in Thread

On Wednesday 25 July 2007 22:06:17 cultural_sublimation wrote:

> 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?

There are two ways to interpret your question:

1. Must I box the result in the variant type only to unbox it?

2. Are the run-time tests necessary?

To which the separate answers are:

1. You do not need to box and then unbox. You can avoid this using
higher-order functions as I showed (generating the unboxed type directly).

2. The run-time tests are necessary because you've reach the boundary of
static typing: the database is not under OCaml's control and is not
statically typed so you must introduce run-time type checks yourself at some
point (but not at two points as you currently are).

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
OCaml for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists/?e

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