Generating Haskell with Haskell
If the power of GHC Generics is not enough, that is, you really need to generate code that isn't derivable from the structure of datatypes, the solution you're looking for is Template Haskell (TH). TH is much more sophisticated than the C preprocessor. With TH, one basically has the full power of Haskell at one's disposal for code-generation. Like Haskell, Template Haskell will not compile unless it produces at least syntactically correct code.
Code generation should be used sparingly. It is easy to write highly unmaintainable code using Template Haskell. On the other hand, code generation can be an easy route for incorporating non-trivial domain-specific optimizations into a Haskell program. Most often though, Template Haskell is used mostly to replace boilerplate code by code that generates that boilerplate.
Template Haskell code lives in the Q
monad. Take a look at the following code block:
-- module Language.Haskell.TH data Q a -- instances...