[gambit-list] How to save s-expressions

Marc Feeley feeley at iro.umontreal.ca
Sat Oct 27 08:44:49 EDT 2012

Le 2012-10-27 à 4:31 AM, Richard Prescott <rdprescott at gmail.com> a écrit :

> Good morning everybody,
> Forgive my ignorance, I am just learning.
> In order to embrace the "code is data" philosophy [1], I want to load and save data as s-expressions within files.  I figured the load using (read (open-input-file "data.scm")).
> How can I save?
> Thanks in advance.
> Richard

While it does work, your code does not close the input-port and relies on the garbage collector to do this, which is a bad idea (because you may run out of file descriptors before a garbage collection is triggered).  It is better to use call-with-input-file which closes the port.

Here are better save and restore functions:

;; File: save-restore.scm

(define (save-to-file filename obj)
    (lambda (port) (write obj port))))

(define (restore-from-file filename)
    (lambda (port) (read port))))

(save-to-file "data.txt" '#(1 2 3))

(pp (restore-from-file "data.txt"))


More information about the Gambit-list mailing list