public
Created

Generic pretty printing

  • Download Gist
gpretty.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
{-# language TypeSynonymInstances, FlexibleInstances, DeriveDataTypeable #-}
 
module GPretty where
 
import Data.Data
import Data.Typeable
import Data.Generics.Aliases
 
data Tree a = Node a [Tree a]
deriving (Show, Data, Typeable)
 
testTree = Node "root" [(Node "one" []), (Node "two" [(Node "three" [])])]
 
-- | A class for pretty printing. This isn't generic or used by the generic func
-- below, but we developed it before we understood what we really wanted to do.
class Pretty a where
pretty :: a -> String
 
instance Pretty String where
pretty s = s
 
instance (Pretty a) => Pretty (Tree a) where
pretty tree = pprint 0 tree
where
pprint n (Node name ns) =
replicate (n*2) ' ' ++ pretty name ++ "\n" ++ concatMap (pprint (n+1)) ns
 
-- | Generic pretty printer
gpretty :: Data a => a -> String
gpretty x = gprettys 0 x ""
 
gprettys :: Data a => Int -> a -> ShowS
gprettys n = ( \t ->
showString (replicate (n * 2) ' ')
. (showString . showConstr . toConstr $ t)
. showChar '\n'
. (foldr (.) id . gmapQ (gprettys (n + 1)) $ t)
) `extQ` ((\s -> (showString $ replicate (n * 2) ' ') . shows s . showChar '\n') :: String -> ShowS)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.