Xref: utzoo comp.lang.c:36615 comp.lang.functional:658 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!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 05:25:48 GMT References: <6873@munnari.oz.au> Sender: acha@dravido.soar.cs.cmu.edu Organization: Carnegie Mellon University Lines: 44 In-reply-to: aet@felix.ee.mu.OZ.AU's message of 25 Feb 91 05:21:30 GMT 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. > "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 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