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'
asked Feb 21, 2012 at 6:01
\$\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.

answered Feb 21, 2012 at 8:31
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.