Arc Forumnew | comments | leaders | submitlogin
Pretty Printing Nested Tables
12 points by drcode 5916 days ago | 1 comment
If you're programming "the arc way" you probably have a lot of data in nested tables. Here is a pretty printer that generates a properly formatted table of your data, with optimal columns widths, cropped oversized fields and sorted rows and columns.

Example:

  > (prettytab (obj bob   (obj age 29 favorite-color 'light-pomegranate-pink gender 'male) 
                    alice (obj age 25 favorite-color 'red) 
                    lisa  (obj age 32 gender 'female)))
Generated Output:

       |age|favorite-color |gender
  -----|---|---------------|------
  alice|25 |red            |      
  bob  |29 |light-pomegr...|male  
  lisa |32 |               |female
All key and attribute types are allowed. By default, fields over 15 characters in length are ellipsized. Nils are shown as an empty field.

Here's the source:

  (def abbrev (x (o n 15))
    (let k (tostring:disp x)
      (if (len> k n)        
          (+ (cut k 0 (- n 3)) "...")
          k)))
  
  (def pad (str n)
    (string str (n-of (- n len.str) #\ )))
  
  (def prettytab (tab)
    (apply map 
           (fn fields
             (prall fields #\newline "|"))
           (let f (fn (col)
                    (withs (abcol (map [abbrev (or _ "")] col)
                            wid (apply max (map len abcol))
                            padwid [pad _ wid])
                      (cons (padwid:car abcol) (cons (string:n-of wid #\-) (map padwid cdr.abcol)))))
             (let items (sort (compare < string:car) tablist.tab)
               (cons (f (cons nil (map car items)))
                     (map (fn (att)
                            (f:cons att (map [cadr._ att] items)))
                          (sort (compare < string) (dedup:mappend keys vals.tab)))))))
    (prn))


1 point by prabu 5914 days ago | link

its pretty :)

-----