Problems getting (read) working

Apr 29, 2009 at 11:34 PM
Edited Apr 30, 2009 at 12:12 AM
Hi I have some problems getting (read) working, i have tried this code, both in xacc.ide and IronScheme Console 1.0 Beta 3, but the program seems to get stuck in the read procedure.

Scheme also provides a couple of procedures for reading from the keyboard. The procedure <tt>read</tt> returns the value of the next parsable object that is entered on the keyboard. For example, let's write a procedure that reads input from the keyboard using <tt>read</tt> and then prints out the type of argument together with the argument:
(define blopp
(lambda ()
(let ((a (read)))
(cond ((number? a) (show "Number" a))
((char? a) (show "Character" a))
((string? a) (show "String" a))
((symbol? a) (show "Symbol" a))
((list? a) (show "List" a))
(else (show "Unknown type" a)))
(blopp))))

(define show
(lambda (type arg)
(begin
(display type)
(display ": ")
(display arg)
(newline))))

The procedure works in the following way:

> (blopp)
5
Number: 5
#\a
Character: a
"foobar"
String: foobar
b
Symbol: b
(1 2 3 4)
List: (1 2 3 4)
#(1 2 3 4)
Unknown type: #(1 2 3 4)

Coordinator
Apr 30, 2009 at 5:53 AM
Hi Jimmy

There are a couple of issues around this, but I'll try make it work for you.

1.  Using (read) in the REPL is normally bad, try running it as a file instead.
2.  Running as a file also wont work as is, due to the way the console accepts lexical data.

To get around this, you will need to use get-line.

Here is a complete example (works in REPL too):

(import (rnrs))

;; this 'read's using line-buffering
(define (read-line)
  (let ((line (get-line (current-input-port))))
    (if (eof-object? line)
        line
        (read (open-string-input-port line)))))

(define blopp
  (lambda ()
    (let ((a (read-line)))
      (cond ((number? a) (show "Number" a))
            ((char? a) (show "Character" a))
            ((string? a) (show "String" a))
            ((symbol? a) (show "Symbol" a))
            ((list? a) (show "List" a))
            (else (show "Unknown type" a)))
      (unless (eof-object? a)            
        (blopp)))))

(define show
  (lambda (type arg)
    (begin
      (display type)
      (display ": ")
      (display arg)
      (newline))))
      
(blopp)