Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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'
share|improve this question
A quick fixup: (\ x -> foo x) is identical to just foo. – ivanm Feb 21 '12 at 9:22

migrated from stackoverflow.com Feb 22 '12 at 14:17

1 Answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.