Xref: utzoo comp.lang.c:36632 comp.lang.functional:660 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!tut.cis.ohio-state.edu!sei!fs7.ece.cmu.edu!o.gp.cs.cmu.edu!pt.cs.cmu.edu!dravido.soar.cs.cmu.edu!acha From: acha@CS.CMU.EDU (Anurag Acharya) Newsgroups: comp.lang.c,comp.lang.functional Subject: Re: function composition in C Message-ID: Date: 28 Feb 91 17:05:57 GMT References: <6873@munnari.oz.au> Sender: acha@dravido.soar.cs.cmu.edu Organization: Carnegie Mellon University Lines: 122 In-reply-to: acha@CS.CMU.EDU's message of 28 Feb 91 05:25:48 GMT In article acha@CS.CMU.EDU (Anurag Acharya) writes: > 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. > Nope. it is possible. As Brad White points out my solution used a compose function whose type was ((int->int) x (int->int) x int)->int whereas the original question asked for a compose function that had the type (int->int) x (int->int) -> (int->int) In this note contains two other solutions. The compose function in the first one looks and feels the same a compose functional in a functional language except that susbequent calls to compose may alter the behaviour of the function returned by compose. The second solution doesnot have this problem but requires an explicit "apply" operation. It pretty much does what functional languages do for composition -- create a closure at composition and use the info during application. The explicit apply operation is needed because unlike Scheme, SML etc., C's nested lexical scopes cannot contain function declarations. anurag ------------------------------------------------------------------------------ First Solution: #include typedef int (*fptr)(); static int (*foo)(), (*bar)(); int compose1 (baz) int baz; { return ((*foo) ((*bar)(baz))); } fptr compose(f,g) fptr f; fptr g; { foo = f; bar = g; return compose1; } 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) ); } ------------------------------------------------------------------------------- Second solution: #include typedef int (*fptr)(); typedef struct CLOS { fptr foo; fptr bar; } closure; closure *compose(f,g) fptr f; fptr g; { closure *tmp; tmp = (closure *) malloc(sizeof(closure)); tmp->foo = f; tmp->bar = g; } int apply (clos,arg) closure *clos; int arg; { return((*(clos->foo))((*(clos->bar))(arg))); } int sqr(x) int x; { return x * x; } int cube(x) int x; { return x * x * x; } int quad(x) int x; { return x * x * x * x; } main() { closure *a, *b; a = compose(sqr,cube); b = compose(sqr,quad); printf("sqr(cube 2) is %d\n",apply(a,2) ); printf("sqr(quad 2) is %d\n",apply(b,2) ); printf("sqr(cube 3) is %d\n",apply(a,3) ); }