views:

431

answers:

1

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.

+4  A: 

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

dsm