Title: Input and Output in Scheme
1Input and Output in Scheme
CS 480/680 Comparative Languages
2Basic I/O
- (display arg) writes arg to standard out
- The second (optional) argument to display is the
output-port to write to. - You get an output port using open-output-file
- You can assign it to a symbol
- (define i (open-output-file myfile))(display
Hello world i) - Likewise, open-input-file opens a file for
reading and returns an input port.
3Reading
- These functions return a string
- (read-char port) one character
- (read-line port) one line
- (read port) one S-expression
- When at EOF, the read functions return an
eof-object, which you can test with(eof-object?
arg) - Write first-line.scheme
4Writing
- These functions write to a port
- (write-char char port) one character
- (write expr port) one S-expression
- expr can be a string, a list, or any other
S-expression - (display expr port) like write
- Write puts around strings, \ in front of
characters, etc. - Display does not
- (newline port) writes a \newline to the port
- Create output.scheme
5Automatic Opening and Closing
- Just like Ruby allows you to pass a block to
open(), Scheme has a mechanism to open a file,
run a subform, and automatically close the file
at the end
(call-with-input-file "hello.txt" (lambda (i)
(let ((a (read-char i)) (b
(read-char i)) (c (read-char i)))
(list a b c)))) (\h \e \l)
See read-print.scheme
6String Ports
- You can read/write from a string as though it was
a file
(define i (open-input-string "hello
world")) (read-char i) \h (read i)
ello (read i) world
7Output String Ports
- The procedure open-output-string creates an
output port that will eventually be used to
create a string
(define o (open-output-string)) (write 'hello
o) (write-char \, o) (display " " o) (display
"world" o)
- The function get-output-string gets the
accumulated string associated with the port
(get-output-string o) "hello, world"
8Loading Files
- (load filename) read each S-expression in a
file and evaluate it as a form. - Files can load other files
- (load-relative filename)
- Path is relative to the location of the current
file
9Eval and Quote
- The special form (eval list) evaluates a list as
code - (define a ( 3 5))a 8
- Quote prevents a list from being evaluated
- (define a ( 3 5))a ( 3 5)(eval a) 8
10Eval-string
- To evaluate a string, you need to use
(eval-string string) - Requires the string.ss library
- (require (lib string.ss))
- See eval-string.scheme
11Exercises
- Write a program that reads in a file of
S-expressions containing fully parenthesized
mathematical expressions in prefix notation.
Your program should print the result of each
expression.
Input File ( 3 7) ( ( 3 7) 5) ( ( 2 5) ( 2
3))
Standard Out 10 50 15