Skip to content

Instantly share code, notes, and snippets.

@oisdk oisdk/tabular.hs
Last active Apr 28, 2019

Embed
What would you like to do?
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
import Data.Semigroup
import Control.Arrow
import Data.Align
import Data.Coerce
import Data.Tuple
newtype Stream a = Stream [a]
instance Monoid a => Monoid (Stream a) where
mempty = Stream []
mappend = coerce (malign @[] @a)
zipLeft f = foldr (\x k ~(y:ys) -> f x y : k ys) (const [])
pad = foldr (\x k n -> x : k (n-1)) (flip replicate ' ')
tabular :: [[String]] -> String
tabular = unlines . map unwords . loop (swap . uncurry f)
where
f xs (Stream ys) = traverse (first Stream . unzip . flip (zipLeft g) ys) xs
g x (Max n) = (Max (length x), pad x n)
ex1 :: String
ex1 = tabular
[ [ "foo", "bar" ]
, [ "x", "xyzzy", "foo" ]
, [ "sik", "kik", "tik" ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.