[Haskell-cafe] Code that writes code

Graham Klyne GK at ninebynine.org
Fri Aug 20 04:17:13 EDT 2010

Maybe not helpful to you at this stage, but...

An alternative to generating source code is to factor out the common
"boilerplate" elements into separate functions, suitably parameterized, and to
use higher order functions to stitch these together.

An example of this kind of approach, which is handled by code generation in some
other languages (e.g. lex, yacc, etc), is the Parsec combinator-based parsing
library (http://www.haskell.org/haskellwiki/Parsec) - instead of generating
code, the syntax "rules" are written directly using Haskell functions and
assemble the common underlying repeated logic dynamically, behind the scenes.

I adopted a development of this approach for a programme with a built-in
scripting language that I implemented some time ago:  the scripting language was
parsed using Parsec, not into a syntax tree, but directly into a dynamically
assembled function that could be applied to some data to perform the scripted
function (http://www.ninebynine.org/RDFNotes/Swish/Intro.html).

What I'm trying to point out here that, rather than go through the step of
generating source code and feeding it back into a Haskell compiler, it may be
possible to use higher order functions to directly assemble the required logic
within a single program.  For me, this is one of the great power-features of
functional programming, which I now tend to use where possible in other
languages that support functions as first class values.


Andrew Coppin wrote:
> I'm working on a small Haskell package. One module in particular 
> contains so much boilerplate that rather than write the code myself, I 
> wrote a small Haskell program that autogenerates it for me.
> What's the best way to package this for Cabal? Just stick the generated 
> file in there? Or is there some (easy) way to tell Cabal how to recreate 
> this file itself?

More information about the Haskell-Cafe mailing list