ZetCode

Scheme reading input

last modified November 25, 2026 Guile 3.0

Input arrives through ports, just like output. The current input port, returned by (current-input-port), is the standard input of the program: the keyboard when the program runs in a terminal, or a file or another program when the input is redirected. The procedures in this article read from the current input port unless they get a port as an argument. The ports and output article covers the output side. The examples run with GNU Guile 3.0.7.

Reading a line

The most common way to read text is a line at a time. read-line comes from the (ice-9 rdelim) module. It reads up to the end of the line and returns the line as a string without the newline character.

name.scm
(use-modules (ice-9 rdelim))

(display "Enter your name: ")
(force-output)

(define name (read-line))

(display "Hello there, ")
(display name)
(display "!")
(newline)
(display (string-length name))
(display " characters read")
(newline)

The program prints a prompt without a newline and waits for a line. force-output writes out anything still waiting in the output buffer. In a terminal Guile shows the prompt even without it, but when the standard output goes to a pipe, the prompt stays in the buffer until the program ends. Calling force-output before reading is a safe habit. In the session below, the name after the prompt was typed by the user.

$ guile name.scm
Enter your name: Lucia
Hello there, Lucia!
5 characters read

Reading numbers

Input is always text. A number must be converted with string->number, which returns #f when the text is not a number. The program has to check for this case, because the user can type anything.

twice.scm
(use-modules (ice-9 rdelim))

(display "Enter a number: ")
(force-output)

(define text (read-line))
(define n (string->number (string-trim-both text)))

(if n
    (begin
      (display "twice that is ")
      (display (* 2 n))
      (newline))
    (begin
      (display "not a number: ")
      (write text)
      (newline)))

string-trim-both removes spaces around the number, which string->number would not accept. The if tests the result of the conversion: any number is a true value, and only a failed conversion gives #f. The program is run twice, once with a number and once with a word.

$ guile twice.scm
Enter a number: 21
twice that is 42
$ guile twice.scm
Enter a number: twenty
not a number: "twenty"

Reading until the end of input

When the input has no more data, the reading procedures return a special end-of-file object, which eof-object? recognises. A program that processes all of its input reads in a loop until it gets this object. In a terminal, the user ends the input with Ctrl+D; usually the input comes from a file.

total.scm
(use-modules (ice-9 rdelim))

(define (sum-lines)
  (let loop ((line (read-line)) (count 0) (total 0))
    (cond ((eof-object? line)
           (values count total))
          ((string-null? (string-trim-both line))
           (loop (read-line) count total))
          (else
           (loop (read-line)
                 (+ count 1)
                 (+ total (string->number line)))))))

(call-with-values sum-lines
  (lambda (count total)
    (display count)
    (display " numbers, total ")
    (display total)
    (newline)))

The named let reads one line per iteration and keeps the count and the total. Blank lines are skipped, and at the end of the input the loop returns both results as multiple values. The shell operator < connects the file numbers.txt to the standard input, so the program reads the file without opening it.

$ cat numbers.txt
12
7.5

30
-4
$ guile total.scm < numbers.txt
4 numbers, total 45.5

Reading characters

read-char reads a single character and needs no module. peek-char returns the next character without consuming it. Reading character by character suits programs that classify or scan text.

letters.scm
(define (count-chars)
  (let loop ((c (read-char)) (letters 0) (digits 0) (others 0))
    (cond ((eof-object? c)
           (list 'letters letters 'digits digits 'others others))
          ((char-alphabetic? c)
           (loop (read-char) (+ letters 1) digits others))
          ((char-numeric? c)
           (loop (read-char) letters (+ digits 1) others))
          (else
           (loop (read-char) letters digits (+ others 1))))))

(display (count-chars))
(newline)

The loop reads characters until the end of input and sorts them into three counts with the predicates from the characters article. The echo command sends a line of text through a pipe; the newline at its end counts as one of the other characters, together with the spaces and the comma.

$ echo "Room 101, 2nd floor" | guile letters.scm
(letters 11 digits 4 others 5)

Reading Scheme data

read parses the next complete Scheme datum from the input: a number, a string, a symbol, or a whole nested list. It skips whitespace and comments. This makes Scheme syntax a ready-made format for configuration and data files.

settings.scm
(define (read-all)
  (let loop ((datum (read)) (acc '()))
    (if (eof-object? datum)
        (reverse acc)
        (loop (read) (cons datum acc)))))

(define settings (read-all))

(display (length settings))
(display " settings")
(newline)

(for-each (lambda (entry)
            (write (car entry))
            (display " -> ")
            (write (cdr entry))
            (newline))
          settings)

(display (* (cadr (assq 'width settings))
            (cadr (assq 'height settings))))
(newline)

read-all calls read until the end of input and collects the data in a list. Each line of the settings file is a list whose first element is a symbol, so the result works as an association list, and assq finds the width and the height. The comment on the first line of the file is skipped by the reader. read only parses the data; it never evaluates it.

$ cat settings.txt
; window settings
(width 800)
(height 600)
(title "Editor")
(colors red green blue)
$ guile settings.scm < settings.txt
4 settings
width -> (800)
height -> (600)
title -> ("Editor")
colors -> (red green blue)
480000

Input string ports

An input string port reads from a string, the counterpart of the output string ports. open-input-string creates one, and with-input-from-string makes a string the current input port while a procedure runs. All reading procedures work on them, which is handy for parsing text that a program already holds, and for testing code that reads input.

strinput.scm
(use-modules (ice-9 rdelim))

(define port (open-input-string "3 4.5 1/2 -7"))

(define (read-numbers port)
  (let loop ((n (read port)) (acc '()))
    (if (eof-object? n)
        (reverse acc)
        (loop (read port) (cons n acc)))))

(define numbers (read-numbers port))
(display numbers)
(newline)
(display (apply + numbers))
(newline)

(define lines (open-input-string "first line\nsecond line\nlast"))
(write (read-line lines))
(newline)
(write (read-char lines))
(write (peek-char lines))
(write (read-char lines))
(newline)
(write (read-line lines))
(write (read-line lines))
(write (read-line lines))
(newline)

(with-input-from-string "(a b) 42 \"text\""
  (lambda ()
    (write (list (read) (read) (read) (eof-object? (read))))
    (newline)))

read turns the text "3 4.5 1/2 -7" into four numbers of different kinds; their sum is inexact because one of them is. The second port is read with all three procedures. After the first line, read-char takes the s of the second line, peek-char looks at the e without taking it, and the next read-char takes it. The last line has no newline at its end, and the call after it returns the end-of-file object, written as #<eof>. In the last part the three data are read from the current input port.

$ guile strinput.scm
(3 4.5 1/2 -7)
1.0
"first line"
#\s#\e#\e
"cond line""last"#<eof>
((a b) 42 "text" #t)

Reading CSV lines

Many data files have one record per line with fields separated by commas. After read-line, the fields are separated with string-split and converted where needed.

grades.scm
(use-modules (ice-9 rdelim))

(define (parse-row line)
  (let ((fields (string-split line #\,)))
    (cons (car fields)
          (map string->number (cdr fields)))))

(define (average xs)
  (exact->inexact (/ (apply + xs) (length xs))))

(define header (string-split (read-line) #\,))
(display (cdr header))
(newline)

(let loop ((line (read-line)) (best #f))
  (if (eof-object? line)
      (begin
        (display "best: ")
        (display (car best))
        (newline))
      (let* ((row (parse-row line))
             (avg (average (cdr row))))
        (display (car row))
        (display ": ")
        (display (cdr row))
        (display " average ")
        (display avg)
        (newline)
        (loop (read-line)
              (if (or (not best) (> avg (cdr best)))
                  (cons (car row) avg)
                  best)))))

The first line of the file is a header with the column names. Each following line becomes a pair of a name and a list of numbers. The loop prints every student's average and carries the best student so far as a pair, which starts as #f. This simple splitting assumes that fields contain no commas; quoted fields need a real CSV parser.

$ cat grades.csv
name,maths,physics,history
Eva,92,85,78
Tomas,64,71,88
Jana,81,95,90
Peter,55,60,72
$ guile grades.scm < grades.csv
(maths physics history)
Eva: (92 85 78) average 85.0
Tomas: (64 71 88) average 74.33333333333333
Jana: (81 95 90) average 88.66666666666667
Peter: (55 60 72) average 62.333333333333336
best: Jana

Reading the whole input

Sometimes it is easier to read the entire input into one string and process it afterwards. get-string-all from the (ice-9 textual-ports) module reads everything up to the end of input.

wordcount.scm
(use-modules (ice-9 textual-ports))

(define text (get-string-all (current-input-port)))

(define (count-words text)
  (length (filter (lambda (w) (not (string-null? w)))
                  (string-split text char-whitespace?))))

(display (list 'lines (string-count text #\newline)
               'words (count-words text)
               'characters (string-length text)))
(newline)

(define longest
  (let loop ((words (string-split text char-whitespace?)) (best ""))
    (cond ((null? words) best)
          ((> (string-length (car words)) (string-length best))
           (loop (cdr words) (car words)))
          (else (loop (cdr words) best)))))

(display longest)
(newline)

The program counts lines, words, and characters, like the wc command. string-split also accepts a predicate instead of a character, so char-whitespace? splits on spaces and newlines alike; the empty strings between neighbouring separators are removed before counting. The second part finds the longest word; of two words with the same length, the first one wins.

$ cat poem.txt
The sun goes down
behind the hill,
the night is near
and all is still.
$ guile wordcount.scm < poem.txt
(lines 4 words 15 characters 71)
behind

Asking until the input is valid

An interactive program should not fail on a typing error. It can repeat the question until the answer is acceptable. The validation is passed in as a predicate, so one procedure serves all questions.

ask.scm
(use-modules (ice-9 rdelim))

(define (ask prompt valid?)
  (display prompt)
  (force-output)
  (let ((line (read-line)))
    (cond ((eof-object? line) #f)
          ((valid? (string->number (string-trim-both line)))
           (string->number (string-trim-both line)))
          (else
           (display "please try again")
           (newline)
           (ask prompt valid?)))))

(define (age? n)
  (and (exact-integer? n) (<= 0 n 150)))

(define (rating? n)
  (and (real? n) (<= 1 n 5)))

(define age (ask "Age: " age?))
(define rating (ask "Rating from 1 to 5: " rating?))

(if (and age rating)
    (begin
      (display (list 'age age 'rating rating))
      (newline))
    (begin
      (display "input ended")
      (newline)))

ask prints the prompt, reads a line, and converts it. When the predicate accepts the number, ask returns it; otherwise it prints a message and calls itself again. age? wants a whole number from 0 to 150, and rating? any real number from 1 to 5. If the input ends, ask returns #f, and the program reports it. In the second session the user pressed Ctrl+D at the second prompt.

$ guile ask.scm
Age: abc
please try again
Age: 200
please try again
Age: 31
Rating from 1 to 5: 7
please try again
Rating from 1 to 5: 4.5
(age 31 rating 4.5)
$ guile ask.scm
Age: 31
Rating from 1 to 5: input ended

Source

Input and Output — GNU Guile Reference Manual

Line Oriented and Delimited Text — GNU Guile Reference Manual

In this article we have read lines with read-line, converted text to numbers, read until the end-of-file object, read characters with read-char and peek-char, parsed Scheme data with read, read from strings, split CSV lines into fields, read the whole input with get-string-all, and asked again until the input was valid. The files article applies the same procedures to ports opened on files, and the strings article covers the procedures used to take the lines apart.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.