Version française
Home     About     Download     Resources     Contact us    
Browse thread
Marshal and Polymorphism
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jonathan Bryant <jtbryant@v...>
Subject: Re: [Caml-list] Marshal and Polymorphism
Yeah, I'm sorry I wasn't real clear.  Let me try again:

This code works:

module Test :
    sig
        type ('a, 'b) t
        val create : 'a -> 'b -> ('a, 'b) t
        val serialize : ('a, 'b) t -> string
        val deserialize : string -> ('a, 'b) t
        val get_word : ('a, 'b) t -> 'a
        val get_index : ('a, 'b) t -> 'b
    end
    =
    struct
        type ('a, 'b) t = { word : 'a; index : 'b };;
        let create x y = { word = x; index = y };;
        let serialize x = Marshal.to_string x [];;
        let deserialize x = (Marshal.from_string x 0 : ('a, 'b) t);;
        let get_word x = x.word;;
        let get_index x = x.index;;
    end
;;

let _ =
    let x = Test.create "Hello" 1 in
    let ser_data = Test.serialize x in
    let deser_data = Test.deserialize ser_data in
    Printf.printf "%s: %d\n" (Test.get_word deser_data) (Test.get_index
deser_data);
;;

My question is:  Will this /always/ work (given that the type of data I
read out of the file is the same)?  Is it really that simple?

On Thu, 2005-08-04 at 13:06 -0700, Stephane Glondu wrote:
> Hi,
> 
> Jonathan Bryant wrote:
> > If I make the module have
> > 
> > type = ('a, 'b) t
> > 
> > in the module definition, can I use
> > 
> > (Marshal.from_string ... : 'a)
> > 
> > and get whatever 'a was defined as in the definition.
> 
> In the way I understood your message, you cannot. However, if you do
> something like :
> 
> let get (table : ('a, 'b) t) index =
>   (Marshal.from_string ... : 'a)
> 
> The 'a type variable must be bound /inside/ a surrounding function
> (and (Marshal.from_string val : 'a) should be forbidden outside a
> function).
> 
> > For example, if
> > it was a (string * int) t, would the function return a string? 
> 
> Now, yes.
> 
> > Or would
> > this be redundant (since Marshal.from_string already returns 'a)?
> 
> No! Actually, the return type of Marshal.from_string is [forall 'a.
> 'a], so it is different from any other 'a which could be already bound
> at this moment. Therefore, you must explicitly tell the return type of
> Marshall.from_string, even if it is polymorphic.
> 
> I hope this is clear.
> 
> Best regards,
> 
-- 
*=========================*
|Jonathan Bryant          |
|Valdosta State University|
|Information Technology   |
|System Operations        |
|-------------------------|
|jtbryant@valdosta.edu    |
|x6358                    |
*=========================*