[plt-scheme] read, read-line

From: Eli Barzilay (eli at barzilay.org)
Date: Fri Jan 13 18:24:02 EST 2006

On Jan 13, Chongkai Zhu wrote:
> ======= At 2006-01-13, 15:11:17 Eli Barzilay wrote: =======
> >
> >That's not enough information.  This can depend on how your terminal
> >interacts with things, or perhaps if you run it in DrScheme or not.
> >To inspect a difference in behavior just for `read' and `read-line'
> >you should come up with an expression that shows a difference given
> >some fixed input (using something like open-input-string).
> >
> >(I did try several combinations, including yours, and saw no
> >difference.  If you see a difference in DrScheme then this is
> >unrelated to what `read'/`read-line' do.)
> Yes, I'm using DrScheme.
> But as you suggested, I just tried what happens in MzScheme, only to
> find that (read-line) always return "#\r", both in v209 and in
> v300.3 on my Windows.

This happens because the REPL will read one expression, so the newline
that follows it is still in the input buffer.

> So now I'm quite confused. What should my program be if
> it will occasionally ask the user to input a S-exp
> it will occasionally ask the user to input a string
> it should work both under MzScheme and DrScheme
> ???

You will probably want to flush the input buffer after reading an
s-expression.  Something like `read-bytes-avail!*' is probably going
to be best for that, but I'm not sure how that will interact with

In any case, the following code seems to be doing what you want:

  (define flush-input
    (let ([buf (make-bytes 10)])
      (lambda ()
        (let loop ()
          (let ([n (read-bytes-avail!* buf)])
            (unless (or (eof-object? n) (zero? (read-bytes-avail!* buf)))
  (define (flush-and- read) (flush-input) (read))
  (list (flush-and- read)
        (flush-and- read-line)
        (flush-and- read)
        (flush-and- read-line))

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!

Posted on the users mailing list.