Search code examples
common-lispclos

How do I best save/read data structures?


I want to write some data structures pointed to by FOO and BAR to a file, and to read the data structures back into the symbols FOO and BAR when I start a new session of Common Lisp.

It would appear *PRINT-READABLY* allows objects to be printed in a fashion that can be read back in by READ, and I can change how objects are printed using (defmethod print-object ...). Since the objects should be printed in a way acceptable to READ, I shouldn't have to define any further methods for reading the object back in.

But is there a way to tie each written data structure to its corresponding symbol, without having to rely on the order the data structures are written and read in?


Solution

  • If I understand correctly, you could store the values and associated symbols as pairs in the file, so something like this:

    (x . (1 2 3 4))
    (y . (6 7 8 1))
    

    And when you parse it out, use something like this:

    (let ((pair (read))
      (set (car pair) (cdr pair)))