7.4  Input and Output: S-expressions


read : IPort  →  S-expression

Given an IPort, read those characters from the port that form an S-expression and produce it.


If the file is looks like this

10

the S-expression is 10.


If the file looks like this

hello

the S-expression is 'hello.


If the file looks like this

(hello world)

the result is (list 'hello 'world).


If the file looks like this

((ALICE 1)
 (BOB 2)
 (CARL 3))

the S-expression is

(list (list 'ALICE 1)
      (list 'BOB 2)
      (list 'CARL 3))


In short, read adds list and quote (’) where needed.

But where do you get an input port from?


Like this:

open-input-file : String  →  IPort
\end{minipage}\hfil\begin{minipage}[b]{2.2in}
\end
\end{minipage}\par\bigskip\par{schemebox}}{Find a file by name
(string), open it, and make it available as an (input) \scheme{Port}.}

\lll{So composing the two functions is useful:

\begin{schemebox}
(read (open-input-file "gradebook.txt"))
If the name of your gradebook file is "gradebook.txt", then this reads an entire grade book.


If "gradebook.txt" contains this:

((ALICE 49 81 64)
 (BOB   16 31 27)
 (CARL  27 64 8))

...then the expression produces:
  (list (list 'ALICE 49 81 64)
        (list 'BOB   16 31 27)
        (list 'CARL  27 64 8))


Of course, this isn’t quite what our data definition says.

(define gradebook
  (map (lambda (raw-gbe)
         (make-gbe
	   (first raw-gbe)
	   (rest raw-gbe)))
       (read 
         (open-input-file 
           "gradebook.txt"))))