Next: , Previous: POSIX-Style Testing, Up: Top


49 Pretty Printing

The module (ice-9 pretty-print) provides the procedure pretty-print, which provides nicely formatted output of Scheme objects. This is especially useful for deeply nested or complex data structures, such as lists and vectors.

The module is loaded by simply saying:

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

This makes the procedure pretty-print available. As an example how pretty-print will format the output, see the following:

     (pretty-print '(define (foo) (lambda (x)
     (cond ((zero? x) #t) ((negative? x) -x) (else (if (= x 1) 2 (* x x x)))))))
     -|
     (define (foo)
       (lambda (x)
         (cond ((zero? x) #t)
               ((negative? x) -x)
               (else (if (= x 1) 2 (* x x x))))))
— Scheme Procedure: pretty-print obj [port [keywords ...]]

Pretty-print obj to current output port. Optional second arg port specifies another port to use. Alternatively, you can also use #:port to specify the port. As a special case, if port is #f, return the string, instead.

Formatting can be controlled by a number of additional keyword arguments: Each line in the output is preceded by the string #:per-line-prefix, which is empty by default. The output lines will be at most #:width characters wide; the default is 79. If #:display? is true, display rather than write representation will be used. If #:escape-strings? is true (and #:display? is not true), replace tabs, newlines, formfeeds and carriage returns in strings with the character sequences \t, \n, \f and \r, respectively.

Beware: Since pretty-print uses it's own write procedure, it's output will not be the same as for example the output of write. Consider the following example.

     (write (lambda (x) x))
     -|
     #<procedure #f (x)>
     
     (pretty-print (lambda (x) x))
     -|
     #[procedure]

The reason is that pretty-print does not know as much about Guile's object types as the builtin procedures. This is particularly important for smobs, for which a write procedure can be defined and be used by write, but not by pretty-print.