function composition in C
Christopher R Volpe
volpe at kirkwood.crd.ge.com
Fri Mar 1 09:34:32 AEST 1991
In article <ACHA.91Feb28002548 at DRAVIDO.CS.CMU.EDU>, acha at CS.CMU.EDU
(Anurag Acharya) writes:
|>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.
|>> "compose" is a one-liner in any functional language,
|>> but I suspect that it is, given the above constraint, impossible in C.
|>
|>Nope. it is possible.
|>
|>Example:
|>
|>#include <stdio.h>
|>
|>int compose (foo,bar,baz)
|>int (*foo) ();
|>int (*bar) ();
|>int baz;
|>{
|> return ((*foo) ((*bar)(baz)));
|> }
This is not a compose function, because it does not take two functions
are return a FUNCTION. Compose should behave as the original poster
specified: (compose(sqr,cube))(2) == 64.
Try something along the lines of the following:
(Assume a stack of function pointers with push and pop functions)
typedef int (*pfi)(int) /* pointer to funtion taking int and returning int */
void push(pfi);
pfi pop(void);
int compose_aux(int arg)
{
pfi f1,f2;
f2 = pop();
f1 = pop();
return f1(f2(arg));
}
pfi compose(pfi f1, pfi f2)
{
push(f1);
push(f2);
return compose_aux;
}
This is just the basic concept, I haven't tested it.
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com
More information about the Comp.lang.c
mailing list