Freewind
Freewind

Reputation: 198198

How to read all lines from console and output them to console in Scheme?

I want to read all lines from console and put them in a list, how to do it in Scheme?

Say, when the program is running, user will input many lines in the console:

aaaa
1111
bbbbb
ccc
2323
dddd
4444

And my Scheme code will read all of them and filtering the numbers and output them to console.

How to do that?

Upvotes: 1

Views: 540

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Here's a function that keeps reading from the default input port and displays it to the default output port.

(define (read-and-display)
  (let ((x (read)))
    (if (not (eof-object? x))
      (begin
        (display x)
        (newline)
        (read-and-display)))))

If your Scheme implementation supports unless, the above function can be simplified to:

(define (read-and-display)
  (let ((x (read)))
    (unless (eof-object? x)
        (display x)
        (newline)
        (read-and-display))))

Upvotes: 1

Related Questions