Xref: utzoo comp.lang.c:36642 comp.lang.functional:661 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!helios!bcm!dimacs.rutgers.edu!seismo!ukma!rex!samsung!zaphod.mps.ohio-state.edu!rpi!crdgw1!kirkwood!volpe From: volpe@kirkwood.crd.ge.com (Christopher R Volpe) Newsgroups: comp.lang.c,comp.lang.functional Subject: Re: function composition in C Message-ID: <17191@crdgw1.crd.ge.com> Date: 28 Feb 91 22:34:32 GMT References: <6873@munnari.oz.au> Sender: news@crdgw1.crd.ge.com Reply-To: volpe@kirkwood.crd.ge.com (Christopher R Volpe) Followup-To: comp.lang.c Lines: 58 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. |>> 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))); |> } 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@crd.ge.com