[Haskell-cafe] Producing fortran/C code with haskell?

David Roundy droundy at abridgegame.org
Fri Jan 30 20:45:51 EST 2004

On Fri, Jan 30, 2004 at 07:32:53PM +0100, Vincenzo aka Nick Name wrote:
> I seem to recall a discussion, don't know if it was here or on 
> comp.lang.functional, where somebody said he uses haskell to generate 
> fortran code.
> That fascinated me a lot, because that would mean being able to generate 
> a program already specialized for a specific input, by first reading 
> input in haskell and then producing code (fortran, but could be C 
> either) - and because I guess it can add static safety exploiting 
> haskell types. Since we already have that nice syntax for monads those 
> programs should be readable, too.
> Where could I find information on such topics, or existing libraries to 
> generate programs with haskell? Is somebody willing to share what (s)he 
> already did?

I've used haskell to generate C code for a few inner loops.  You can browse
my code at the following link:


The haskell code is all in the hsrc directory, and StepGen.lhs is the
module that does the work, assisted a bit by Complex.lhs and
YeeLattice.lhs, which define stuff releting to complex numbers and the Yee
lattice respectively.  The files step_d_gen.hs, etc., each create a program
whose output is a chunk of C++ code that is then #included into the
relevant function.

My code is ugly and not very general at all, but it has allowed me to
cobble together something that generates the inner loop in something
resembling a reasonable manner.  The main problem the code tries to solve
is situations where you'd like to code

for (int i=0;i<imax...) {
  out[i][j][k] = f[i][j][k] + g[i];
  if (a) out[i][j][k] += x;
  if (b) out[i][j][k /= y[i][j][k];

but for speed reasons you need to put the if (a) and if (b) on the outside
of the loop, but you don't want to code each case by hand, since that would
create an unmaintainable mess.  In my framework, the above would be
accomplished (creating four separate loops for all combinations of a and b)
by something like

whether_or_not "a" $ whether_or_not "b" $
do_block "for (int i=0;i<imax...)"
[doexp "out[i][j][k] = f[i][j][k] + g[i]",
 if_ "a" $ doexp "out[i][j][k] += x",
 if_ "b" $ doexp "out[i][j][k] /= y[i][j][k]"

There are also features relating to expressions, which can simplify
arithmetic for cases where a variable is known to be one or zero.  But in
general, it's an ugly piece of code...
David Roundy

More information about the Haskell-Cafe mailing list