Re: Question about GADT
"Stephane Legrand [email protected] [ocaml_beginners]" <[email protected]> Sat, 5 Dec 2015 00:04:57 +0100
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <[email protected]> |
Ok. Thank you very much for your help. On 04.12.2015 08:36, Gabriel Scherer [email protected] [ocaml_beginners] wrote: > 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. > >> > > >> >