[Haskell-cafe] how to generate source code from TH Exp?

Stefan Kersten sk at k-hornz.de
Thu May 12 19:04:13 CEST 2011


On 5/12/11 4:03 PM, Serguey Zefirov wrote:
> Just pretty-print a Exp.
>
> It seems that "show $ ppr exp" will produce exactly what you need.
>
> The same goes for Dec (declarations), etc.

ah ok, thanks!

fwiw, here's a way to extract a list of module names that need to be 
imported, adapted from an example by Neil Mitchell using generics:

extractModules :: Data a => a -> [String]
extractModules = sort . nub . everything (++) ([] `mkQ` f)
      where f (NameQ x) = [modString x]
            f (NameG _ _ x) = [modString x]
            f _ = []

which can be used to output a source code module:

mkModule :: (Data a, Ppr a) => [String] -> String -> a -> String
mkModule exts name e =
     unlines ([ "{-# LANGUAGE " ++ intercalate ", " exts ++ " #-}"
              , "module " ++ name ++ " where" ]
              ++ map ("import qualified " ++) (extractModules e))
              ++ show (ppr e)

good enough for now ;)

<sk>



More information about the Haskell-Cafe mailing list