Re: Question about GADT

"Gabriel Scherer [email protected] [ocaml_beginners]" <[email protected]> Fri, 4 Dec 2015 08:36:25 +0100
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <CAPFanBHZR6GfOomZEq=81W=9ux5e6kYGRf2eST89b7nTVuP__g@mail.gmail.com>
This is possible, but when your data is of type (t), you have to
consider two cases: it may be (a data) for any type (a), (int) or
(string). If you had a (int data) or a (string data), you would know
the type of the content, but (t) can be any of those.

let () =
   match test with
   | Wrap (Int n) -> print_int n
   | Wrap (String s) -> print_string s


On Fri, Dec 4, 2015 at 12:15 AM, Stephane Legrand [email protected]
[ocaml_beginners] <[email protected]> wrote:
> I'm trying to unwrap the data built with "data_int" or "data_string". Ie
> i'm trying to retrieve the original value "v" used in "data_int" or
> "data_string" but only by using the "to_ocaml_value" function. I don't
> even know if it's possible?
>
> On 03.12.2015 23:42, Gabriel Scherer [email protected]
> [ocaml_beginners] wrote:
>> The program has a type error, as (v) in the last sentence could be
>> either (Int n) or (String s). The compiler is right to complain. What
>> are you trying to do?
>>
>> On Thu, Dec 3, 2015 at 11:34 PM, Stephane Legrand [email protected]
>> [ocaml_beginners] <[email protected]> wrote:
>>  > Hello,
>>  >
>>  > I'm trying to run the code below. The compiler gives me an error for the
>>  > "print_endline x" line: "This expression has type ex#0 but an expression
>>  > was expected of type string". Is there a way to fix this error? If this
>>  > kind of thing is doable with GADT? Thank you.
>>  >
>>  > type _ data =
>>  > Int : int -> int data
>>  > | String : string -> string data
>>  >
>>  > type t =
>>  > Wrap : _ data -> t
>>  >
>>  > let data_int v = Wrap(Int v)
>>  > let data_string v = Wrap(String v)
>>  >
>>  > let to_ocaml_value : type a. a data -> a = function
>>  > | Int v -> v
>>  > | String v -> v
>>  >
>>  > let test = data_string "test"
>>  >
>>  > let () =
>>  > match test with
>>  > | Wrap v ->
>>  > let x = to_ocaml_value v in
>>  > print_endline x
>>  >
>>  >
>>  > Regards,
>>  > Stéphane.
>>  >
>>  >
>
>
>
> ------------------------------------
> Posted by: Stephane Legrand <[email protected]>
> ------------------------------------
>
> Archives up to December 31, 2011 are also downloadable at http://www.connettivo.net/cntprojects/ocaml_beginners
> The archives of the very official ocaml list (the seniors' one) can be found at http://caml.inria.fr
> Attachments are banned and you're asked to be polite, avoid flames etc.
> ------------------------------------
>
> Yahoo Groups Links
>
>
>