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

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

by Jon Harrop :: Rate this Message:

Reply to Author | View in Thread

On Wednesday 25 July 2007 13:52:55 cultural_sublimation wrote:
>   type movie_t = string * int * bool
>   type actor_t = string * int

Use records here to be more descriptive:

module Movie = struct
  type t = {name: string; foo: int; bar : bool}

  let of a = function
    | [|name; foo; bar|] ->
        {name=name; foo=int_of_string foo; bar=bool_of_string bar}
    | _ -> invalid_arg "Movie.of"
end

>   type query_result = Movie of movie_t | Actor of actor_t

Remove this type.

>   let process_query array_converter converter_template result =
>       let size = Array.length result in
>       let converted = Array.make size converter_template in
>       for i = 0 to size-1 do
>           converted.(i) <- array_converter (result.(i))
>       done;
>       converted

That is "Array.map".

>   let process_movies result =
>       let converter_template = Movie ("", 0, false) in
>       process_query array_to_movie converter_template result
>
>   let process_actors result =
>       let converter_template = Actor ("", 0) in
>       process_query array_to_actor converter_template result

The conversion is now trivial:

  Array.map Movie.of

so I would not bother factoring it out. Instead, have a query_movie function:

  let query_movie db query = Array.map Movie.of (Sql.query db query)
  let query_actor db query = Array.map Actor.of (Sql.query db query)

> This is all fine and dandy, except that because of the unification,
> the signature of both process_movies and process_actors is the same:
>
>
>   val process_movies : string array array -> query_result array
>   val process_actors : string array array -> query_result array
>
>
> My question is the following: how do I undo the unification of movie_t
> and actor_t, so that externally, the signatures of these functions are
> different? (listed below).

You must make them separate types (like my records).

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