[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: how to read "structs" from disk file ?



Also consider using the print-convert library. This code:

  (require-library "pconvert.ss")
  (define-struct a (b c))
  (call-with-output-file "tmp.ss"
    (lambda (port)
      (write (print-convert (make-a 1 2)) port))
    'truncate)

produces:

  (make-a 1 2)

in the file tmp.ss. Then, you can just load the file. For more info,
see the print-convert docs in Help Desk.

Matthias's explanation below is correct, but as long as you are careful
to evaluate the define-struct expression only once it will not be a
problem. (Basically the solution above automates his solution below.)

Robby

Quoting Matthias Felleisen:
> 
> Here is about the only way to read and write structures: 
> 
>   (print-struct #t) 
> 
>   (define-struct posn (x y))
> 
>   (define (vector->posn v)
>     (apply make-posn (cdr (vector->list v))))
> 
>   (with-output-to-file "foo.txt"
>     (lambda ()
>       (printf "~a~n" (list (make-posn 1 2) (make-posn 3 4)))))
> 
>   (define x (map vector->posn (with-input-from-file "foo.txt" read)))
> 
> That's what I do in a similar context (maintaining "Daddy's bank accounts"
> for my kids :-). 
> 
> Explanation: It is impossible to read structures back properly because
> define-struct is generative. That is, every evaluation of define-struct
> creates a different class of structured data. Furthermore, reading may
> happen in a context where the structure hasn't been defined, so read cannot
> call make-s.
> 
> -- Matthias