Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do input with racket?

Tags:

scheme

racket

What's the best way to read input from stdin in racket?

In particular I'd like something like cin from c++ or scanf from c where I specify the types of things I want read and they are returned.

like image 734
Cam Avatar asked Nov 14 '11 10:11

Cam


3 Answers

read-line is easy. To be portable across Unix and Windows, additional option is required.

(read-line (current-input-port) 'any)

Return and linefeed characters are detected after the conversions that are automatically performed when reading a file in text mode. For example, reading a file in text mode on Windows automatically changes return-linefeed combinations to a linefeed. Thus, when a file is opened in text mode, 'linefeed is usually the appropriate read-line mode.

So, 'any is required to be portable when the input port is not a file (standard input).

Test program:

#lang racket
(let loop ()
    (display "Input: ")
    (define a (read-line (current-input-port) 'any))
    (printf "input: ~a, length: ~a, last character: ~a\n"
        a
        (string-length a)
        (char->integer (string-ref a (- (string-length a) 1))))
    (loop))

In Windows, replace (read-line (current-input-port) 'any) with (read-line) and see what happens.

like image 199
KIM Taegyoon Avatar answered Oct 06 '22 04:10

KIM Taegyoon


You can do pretty much everything you want to... at the low level, I would suggest (read-line) and (read-bytes). For higher-level processing (as e.g. scanf does), I would suggest a regexp-match on the input. For instance

(regexp-match #px" *([0-9]+)" (current-input-port))
like image 36
John Clements Avatar answered Oct 06 '22 05:10

John Clements


I'd use the read procedure for the general case. If the data type to be read is known beforehand, use read-char, read-string, read-bytes.

Also, take a look at this implemenation for reading formatted input - a scanf in Scheme.

like image 42
Óscar López Avatar answered Oct 06 '22 03:10

Óscar López