How do I pretty-print a table in Haskell?
Asked Answered
B

1

17

I would like to prettyprint a table-like data structure in Haskell (a list of columns).

For example...

Table [
    StrCol "strings" ["a", "bc", "c"],
    IntCol "ints" [1, 30, -2],
    DblCol "doubles" [2.0, 4.5, -3.2]]

Should render something like...

strings ints doubles
    "a"    1     2.0
   "bc"   30     4.5
    "c"   -2    -3.2

Currently I have implemented this functionality in Text.PrettyPrint that comes with the most recent version of the Haskell Platform. Unfortunately the <+> operator orients multi-line documents "diagonally" from each other.

eg

(text "a" $+$ text "b") <+> (text "c" $+$ text "d")

renders as

a
b c
  d

rather than

a c
b d

As a result, I transpose the cells and merge them horizontally first, then vertically, but this results in the columns not being aligned.

In an older table pretty-printing question, augustss refers to adding some more code to have the columns automatically adapt to the widest entry.

I'm guessing that "sizedText" with the maximum length of each column would do this, except that this function doesn't appear to be part of the Haskell Platform Text.PrettyPrint module (I think it's in the closely related Text.Pretty package).

What's the simplest non-hacky way of implementing this pretty-print functionality? This is a small part of my project so I'd like to avoid writing my own pretty-printing, and I'd prefer to avoid module dependencies if I can.

Brettbretz answered 24/4, 2012 at 6:36 Comment(1)
With pretty-printers you can only print left-to-right, then concatenate lines together. The simplest thing to do is transpose your matrix first, then you can work left to right. Generally you can't find the width of a Doc so where you need padding you will have to add it to the string before you make a Doc with text.Barcus
R
22

http://hackage.haskell.org/package/boxes

The boxes package

A pretty-printing library for laying out text in two dimensions, using a simple box model....

Russian answered 24/4, 2012 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.