[plt-scheme] writing structures

From: Richard C. Cobbe (cobbe at ccs.neu.edu)
Date: Mon Jan 20 12:56:11 EST 2003

Lo, on Monday, January 20, Pedro Pinto did write:

> Hi there,
> I am trying to serialize a structure I created using:
> (define-struct my-struct (field1 field2 field3))
> (define s (make-my-struct 1 2 3))
> Ideally I would like to simply use:
> (write s port)
> and
> (define s (read port))
> Is something like this possible? 

About halfway, yes.

If you have a sufficiently powerful inspector (see section 4.6 of the
MzScheme manual), then you can do something like

(write (struct->vector s) port)

Reading is a bit less straightforward; you'll have to do something like

(define s (parse-foo (read port)))

where parse-foo is a function that takes a vector as its argument and
parses it to an instance of the structure.  Note, by the way, that the
first element in this vector will be a symbol naming the kind of
structure.  You will likely find the match library very helpful in
writing parse-foo.

For the example above:

(define parse-foo
    [#('struct:my-struct field1 field2 field3) 
     (make-my-struct field1 field2 field3)]))


Posted on the users mailing list.