[plt-scheme] Writing structures
[Oops - I sent this to Robby in stead of the list]
Robert Bruce Findler wrote:
> You may also want to check out the print-convert function in the
> pconvert.ss library.
This discussion inspired me to make the following teachpack for my students.
It demonstrates how to use pconvert and eval to read and write structures.
In HTDP there is an exercise where you make a small phonebook program.
They wanted to save the phone and retrieve it later. The problem for me
was that the student language didn't give access to other ports than
stdin and stdout.
> (define out (open-output-file "qux.txt"))
> (write-to-port (list 1 "foo" (make-posn 1 2))
out)
> (close-output-port out)
> (define in (open-input-file "qux.txt"))
> (read-from-port in)
(1 "foo" #(struct:posn 1 2))
> (read-from-port in)
#<eof>
;;; io.scm -- Jens Axel Søgaard -- jan 2003
; IO-teachpack for the advanced student language
(module io mzscheme
(require (lib "pconvert.ss"))
(require (lib "pretty.ss"))
(provide read-from-port write-to-port
open-input-file close-input-port
(rename my-open-output-file open-output-file)
close-output-port)
(abbreviate-cons-as-list #t)
(booleans-as-true/false #t)
(constructor-style-printing #t)
; write-to-port : value port -> (void)
; write a textual representation of v to the port
(define (write-to-port v port)
(pretty-print (print-convert v) port))
; read-from-port : port -> value
; read a textual representation of value and return the corresponding
value
; if the end of port is reached the eof-object is returned
(define (read-from-port port)
(eval (read port)))
; open-output-file : string -> port
; open the file and return an associated port for writing
; if a file with the name already exists, its contents is deleted
(define (my-open-output-file file)
(open-output-file file 'replace)))
--
Jens Axel Søgaard