[comp.theory] function composition in C

aet@felix.ee.mu.OZ.AU (bert) (02/25/91)

	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.

	"compose" is a one-liner in any functional language,
but I suspect that it is, given the above constraint, impossible in C.
(then again, I'm just an undergrad, so what would I know :-)

	Feel free to use pointers wherever they seem appropriate.
	(so the above call could look like:
	(*compose(&sqr,&cube)) (2)	   )

	Many thanks for everyone's helpful comments!

		Bert Thompson.

sane@cs.uiuc.edu (Aamod Sane) (02/26/91)

aet@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.

>	"compose" is a one-liner in any functional language,
>but I suspect that it is, given the above constraint, impossible in C.
>(then again, I'm just an undergrad, so what would I know :-)

>	Feel free to use pointers wherever they seem appropriate.
>	(so the above call could look like:
>	(*compose(&sqr,&cube)) (2)	   )

>	Many thanks for everyone's helpful comments!

>		Bert Thompson.

Write to comp.lang.misc. There was recently a major war on this..

-- 
sane@cs.uiuc.edu
         ==         / \  
-----    ==    *    \_/     -|||- 
         ==     

markh@csd4.csd.uwm.edu (Mark William Hopkins) (02/26/91)

In article <6873@munnari.oz.au> aet@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...