function composition in C
Anurag Acharya
acha at CS.CMU.EDU
Thu Feb 28 16:25:48 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.
> "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)));
}
int sqr(x)
int x;
{
return x * x;
}
int cube(x)
int x;
{
return x * x * x;
}
main()
{
printf("The value is %d\n",compose(sqr,cube,2) );
}
try it out. it works. this version of compose will work for any pair of
int->int functions. liberal use of casts will allow you to write a general
compose as well.
anurag
More information about the Comp.lang.c
mailing list