Search code examples
haskellpretty-print

Haskell Pretty Printing - Accessible, practical library


Assume I have [("bird",3,44),("cat",534,3)] :: [(String,Int,Int)]. What is the simplest way to get a pretty printed result, a la:

bird    3   44
cat   534    3

It seems there are a lot of Haskell pretty printing libraries without a clear favorite, nor many examples.


Solution

  • Most pretty-printing libraries focus around alternative layouts (choosing cleverly when to add newlines, etc.). For something like this, use boxes:

    import Text.PrettyPrint.Boxes
    import Data.List
    table = [("bird",3,44),("cat",534,3)] :: [(String,Int,Int)]
    cols = transpose [ [ animal, show n, show m ] | (animal, n, m) <- table ]
    rendered = render . hsep 2 left . map (vcat left . map text) $ cols
    putStr rendered
    

    Output:

    bird  3    44
    cat   534  3