2
\$\begingroup\$

I need to draw tabulated data given a header as list and rows as list of lists This is what I came up with. I wouldn't say that I like it much. Could you please have a look if it can be done better (I am sure it can) and generally point to any error and possible optimization. Maybe someone has done exact same thing before. Thanks.

import Data.Text (justifyLeft, unpack, pack)
import Data.Char (toUpper)

tDraw :: [String] -> [[String]] -> IO()
tDraw h rs = do
  putChar '\n'
  -- draw header
  mapM_ (\x -> putStr x) header
  putChar '\n'
  -- draw separator line
  mapM_ (\x -> putChar x) (replicate (cell * length header) '=')
  putChar '\n'
  -- draw rows
  mapM_ (\x -> row cell x) rs
  where
    cell = if l < 10 then 12 else l + 2
           where l = (maximum . map (\x -> length x) . concat) (h:rs)
    header = map (\x -> strToUp $ unpack $ justifyLeft cell ' ' (pack x)) h
             where strToUp = map (\c -> toUpper c)
    row n l  = do
      mapM_ (\x -> putStr $ unpack $ justifyLeft n ' ' (pack x)) l
      putChar '\n'
\$\endgroup\$
1
  • \$\begingroup\$ A quick fixup: (\ x -> foo x) is identical to just foo. \$\endgroup\$ Commented Feb 21, 2012 at 9:22

1 Answer 1

2
\$\begingroup\$

It might make sense to use a pretty-printing library to do this. You can use pretty along with the extension pretty-ncols package; or possibly boxes would work as it's aimed at more 2D textual information.

\$\endgroup\$

You must log in to answer this question.