function composition in C
Mark William Hopkins
markh at csd4.csd.uwm.edu
Tue Feb 26 13:22:02 AEST 1991
In article <6873 at munnari.oz.au> aet at felix.ee.mu.OZ.AU (bert) writes:
>
> Does anyone know how to write a compose function in C,
>without writing a Scheme interpreter to do it in.
>
>A call should look something like this:
> (compose(sqr,cube)) (2)
>which would evaluate to 64.
...
You could do it compile-time like this example for composing x^2 and 2*x:
------------------------------------------------------------
#include <stdio.h>
int Compose(F, G, X)
int (*F)(), (*G)(); int X;
{ return (*F)((*G)(X)); }
static int Square(X)
int X;
{ return X*X; }
static int Double(X)
int X;
{ return 2*X; }
static int Square_Double(X)
int X;
{ return Compose(Square, Double, X); }
static int Double_Square(X)
int X;
{ return Compose(Double, Square, X); }
main() {
printf("%d, %d", Square_Double(5), Double_Square(5));
}
------------------------------------------------------------
The declarations above for Square_Double, and Double_Square would be
compile-time lambda abstractions (with X being the variable abstracted
out), but C does not support run-time lambda abstraction.
You'd have to be able to write something like:
int (*Compose(int (*F)(), int (*G)()))() {
int (*H)(int X) { return (*F)((*G)(X)); }
return H;
}
with embedded run-time function declarations...
More information about the Comp.lang.c
mailing list