How to write a custom pretty printer
Asked Answered
A

1

13

A problem that has frequently come up in my career is I have some kind of data structure (perhaps an s-expression) and I want to print it in a human readable form complete with reasonable indentation choices.

Is there a book or blog entry that describes how to do this elegantly? I am interested in the algorithm more than a specific library.

Allow answered 29/4, 2009 at 13:20 Comment(0)
I
17

S-Exps are equivalent to tree structures, if you can pretty-print a tree you can pretty-print an s-exp.

For instance, compare:

(tree
    (value 89)
    (tree
        (value 9)
        nil
        nil)
    (tree
        (value 456)
        nil
        nil))

to:

89
 +- 9
 +- 456

The algorithm is identical, the only difference is the ammount of surrounding data you want to print out.

This paper describes an algorithm for pretty-printing trees

This one describes a pretty-printer for programming languages

Inscrutable answered 29/4, 2009 at 13:31 Comment(2)
The second link is no longer available.Hilburn
The second link is to Derek C. Oppen's 1979 publication "PRETTY PRINTING." It's report number is: CS-TR-79-770. It can currently be found at i.stanford.edu/TR/CS-TR-79-770.html with a direct link at i.stanford.edu/pub/cstr/reports/cs/tr/79/770/CS-TR-79-770.pdfContortive

© 2022 - 2024 — McMap. All rights reserved.