ZetCode

Scheme ports and output

last modified November 25, 2026 Guile 3.0

Every program in this series has printed its results with display, write, and newline. These procedures do not write to the screen directly. They write to a port, an object that stands for a source or destination of characters. The terminal, a file, and a string in memory are all reached through ports, so the same output code works with each of them. This article covers output ports; the reading input article covers input. The examples run with GNU Guile 3.0.7.

Writing to ports

The output procedures take an optional last argument, the port to write to. Without it they use the current output port, which (current-output-port) returns; for a script run from a terminal it is the standard output.

ports.scm
(define out (current-output-port))

(display "Hello there" out)
(newline out)
(write "Hello there" out)
(newline out)
(write-char #\λ out)
(write-char #\newline out)

(display (list (port? out) (output-port? out) (input-port? out)))
(newline)

(define items (list 1.5 #\a "text" 'sym))
(display items)
(newline)
(write items)
(newline)

The program stores the current output port in out and passes it explicitly. write-char writes a single character, here a Greek lambda and a newline. port?, output-port?, and input-port? test what kind of object a value is. The last two lines repeat the difference between the two main output procedures: display writes data for people, and write writes it in the form that Scheme can read back, with quotes around strings and #\ before characters.

$ guile ports.scm
Hello there
"Hello there"
λ
(#t #t #f)
(1.5 a text sym)
(1.5 #\a "text" sym)

Standard error

A program has a second output port for error messages and diagnostics, (current-error-port), which is the standard error stream. Keeping messages there leaves the standard output free for the results, which can then be redirected or piped to another program.

warnings.scm
(define (check-age age)
  (if (and (>= age 0) (< age 150))
      (begin
        (display "age ok: ")
        (display age)
        (newline))
      (let ((err (current-error-port)))
        (display "invalid age: " err)
        (display age err)
        (newline err))))

(for-each check-age '(31 -4 45 200 18))

Valid ages are printed to the standard output, and invalid ones to the standard error. In a terminal both streams appear together, in the order they were written. The second command redirects the standard output to /dev/null, and only the messages remain.

$ guile warnings.scm
age ok: 31
invalid age: -4
age ok: 45
invalid age: 200
age ok: 18
$ guile warnings.scm > /dev/null
invalid age: -4
invalid age: 200

Output string ports

A string port collects the characters written to it in memory. open-output-string creates one and get-output-string returns everything written so far. This is the standard way to build a string from many pieces or to turn a value into the text that write would print.

strport.scm
(define port (open-output-string))

(display "x = " port)
(write 42 port)
(display ", name = " port)
(write "Eva" port)

(define text (get-output-string port))
(display text)
(newline)
(display (string-length text))
(newline)

(define (list->csv items)
  (call-with-output-string
    (lambda (port)
      (let loop ((items items) (first? #t))
        (unless (null? items)
          (unless first? (display "," port))
          (write (car items) port)
          (loop (cdr items) #f))))))

(display (list->csv '(1 2.5 "three" four)))
(newline)
(write (list->csv '()))
(newline)

The first part writes four pieces to the port and takes the result as one string of 20 characters. call-with-output-string creates a string port, passes it to a procedure, and returns the collected string. list->csv uses it to write the items of a list separated by commas; write keeps the quotes of strings. An empty list gives an empty string.

$ guile strport.scm
x = 42, name = "Eva"
20
1,2.5,"three",four
""

Capturing output

with-output-to-string calls a procedure without arguments and makes a new string port the current output port while it runs. All output that would go to the standard output is collected instead, which also works for procedures that do not take a port argument.

capture.scm
(define (print-bar name score)
  (display name)
  (display ": ")
  (display (make-string score #\*))
  (newline))

(print-bar "Eva" 5)

(define captured
  (with-output-to-string
    (lambda ()
      (print-bar "Tomas" 3)
      (print-bar "Jana" 7))))

(display "captured ")
(display (string-length captured))
(display " characters")
(newline)
(write captured)
(newline)
(display (string-upcase captured))

print-bar always prints to the current output port. The first call goes to the terminal; the next two run inside with-output-to-string, and their output ends up in captured. write shows the string with its newlines as \n, and the last line prints it in upper case. When the procedure returns, the previous output port is restored.

$ guile capture.scm
Eva: *****
captured 25 characters
"Tomas: ***\nJana: *******\n"
TOMAS: ***
JANA: *******

The format procedure

Building a line from many display calls is verbose. format from the (ice-9 format) module fills a template with values. The first argument is the destination: #t writes to the current output port, #f returns a string, and a port writes to that port. The template contains directives that start with a tilde.

formatting.scm
(use-modules (ice-9 format))

(define name "Eva")
(define langs '(scheme c python))

(format #t "Name: ~a~%" name)
(format #t "Written: ~s~%" name)
(format #t "~a knows ~d languages: ~a~%" name (length langs) langs)
(format #t "Home directory: ~~/~a~%" (string-downcase name))

(define line (format #f "~a-~a-~a" 2026 11 25))
(write line)
(newline)

(define log-port (open-output-string))
(format log-port "step ~d done~%" 1)
(format log-port "step ~d done~%" 2)
(display (get-output-string log-port))

~a inserts a value as display would show it, and ~s as write would. ~d takes an integer, ~% starts a new line, and ~~ produces a tilde. With #f as destination, format returns the date as a string, and the last part writes two lines to a string port. Guile loads (ice-9 format) by itself the first time format is called, but naming the module makes the dependency clear. Widths, decimal places, and aligned columns are covered in the number formatting article.

$ guile formatting.scm
Name: Eva
Written: "Eva"
Eva knows 3 languages: (scheme c python)
Home directory: ~/eva
"2026-11-25"
step 1 done
step 2 done

Directives for lists and words

Some directives control the template itself. They repeat part of it for each element of a list, choose between two texts, or change the case of the output.

directives.scm
(use-modules (ice-9 format))

(define langs '("Scheme" "C" "Python"))

(format #t "~{~a~^, ~}~%" langs)
(format #t "~{<~a>~}~%" langs)

(define (report-files n)
  (format #t "found ~d file~:p~%" n))

(report-files 1)
(report-files 3)

(define (status ok?)
  (format #t "status: ~:[failed~;passed~]~%" ok?))

(status #t)
(status #f)

(format #t "~@(~a~)~%" "the first letter")
(format #t "~:@(~a~)~%" "every letter")

~{...~} applies the enclosed template to each element of a list, and ~^ stops before the separator after the last element. ~:p looks at the previous argument and prints an s unless it is 1. ~:[no~;yes~] prints the first text for #f and the second for any other value. ~@(...~) capitalises the first letter of its output, and ~:@(...~) converts all of it to upper case.

$ guile directives.scm
Scheme, C, Python
<Scheme><C><Python>
found 1 file
found 3 files
status: passed
status: failed
The first letter
EVERY LETTER

Pretty printing

display and write put a nested list on one line, however long. pretty-print from the (ice-9 pretty-print) module breaks it into lines and indents them. It writes like write, followed by a newline.

pretty.scm
(use-modules (ice-9 pretty-print))

(define person
  '((name . "Eva")
    (age . 31)
    (languages "Scheme" "C" "Python")
    (address (city . "Bratislava") (zip . "81101"))))

(display person)
(newline)
(newline)
(pretty-print person)
(newline)
(pretty-print person #:width 40)
(newline)
(pretty-print '(define (squares n)
                 (let loop ((i 0) (acc '()))
                   (if (= i n)
                       (reverse acc)
                       (loop (+ i 1) (cons (* i i) acc))))))

The association list from the association lists article is too long for one line. With the default width of 79 columns, pretty-print puts each entry on its own line; with #:width 40 it also breaks the nested address. Code is data in Scheme, so the same procedure lays out a quoted definition the way it would look in a source file.

$ guile pretty.scm
((name . Eva) (age . 31) (languages Scheme C Python) (address (city . Bratislava) (zip . 81101)))

((name . "Eva")
 (age . 31)
 (languages "Scheme" "C" "Python")
 (address (city . "Bratislava") (zip . "81101")))

((name . "Eva")
 (age . 31)
 (languages "Scheme" "C" "Python")
 (address
   (city . "Bratislava")
   (zip . "81101")))

(define (squares n)
  (let loop ((i 0) (acc '()))
    (if (= i n)
      (reverse acc)
      (loop (+ i 1) (cons (* i i) acc)))))

Writing to any port

A procedure that produces output should take the port as an optional parameter that defaults to the current output port. The caller then decides where the output goes, and the procedure needs no changes.

report.scm
(use-modules (ice-9 format))

(define stock
  '(("apples" 12 45) ("pears" 4 60) ("plums" 30 12)))

(define* (print-report items #:optional (port (current-output-port)))
  (for-each (lambda (item)
              (let ((name (car item))
                    (count (cadr item))
                    (cents (caddr item)))
                (format port "~a: ~d × ~d cents = ~d cents~%"
                        name count cents (* count cents))))
            items)
  (format port "~d item~:p, ~d cents in total~%"
          (length items)
          (apply + (map (lambda (item) (* (cadr item) (caddr item)))
                        items))))

(print-report stock)
(newline)

(define text
  (call-with-output-string
    (lambda (port) (print-report (cdr stock) port))))

(format #t "the report has ~d lines and ~d characters~%"
        (string-count text #\newline) (string-length text))
(display (string-upcase text))

print-report prints a line for each item in stock and a summary line; prices are whole cents, so the arithmetic stays exact. It is called twice: once without a port, which prints to the terminal, and once with a string port, which collects the report for the last two items. The program then counts the lines of the text with string-count and prints it in upper case. The same procedure could write the report to a file port, as the files article shows.

$ guile report.scm
apples: 12 × 45 cents = 540 cents
pears: 4 × 60 cents = 240 cents
plums: 30 × 12 cents = 360 cents
3 items, 1140 cents in total

the report has 3 lines and 93 characters
PEARS: 4 × 60 CENTS = 240 CENTS
PLUMS: 30 × 12 CENTS = 360 CENTS
2 ITEMS, 600 CENTS IN TOTAL

Source

Input and Output — GNU Guile Reference Manual

Formatted Output — GNU Guile Reference Manual

In this article we have written to the current output port and to explicit ports, sent messages to the standard error, collected output in string ports, captured the output of a procedure with with-output-to-string, filled templates with format, laid out nested data with pretty-print, and written a procedure that prints to any port. The basics article introduced display and write, and the strings article covers the string procedures used on the collected text.

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.