Xref: utzoo comp.lang.c:36685 comp.lang.functional:664 Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!samsung!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c,comp.lang.functional Subject: Re: function composition in C Message-ID: <4860@goanna.cs.rmit.oz.au> Date: 1 Mar 91 06:42:56 GMT References: <6873@munnari.oz.au> Followup-To: comp.lang.c Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 46 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. He then proceded to miss the point completely. The point was *not* to write a function which applies the composition of two functions to a given function, the equivalent of (define (apply-composition f g x) (f (g x))) but a function which returns a new function, which is the composition, the equivalent of (define (make-composition f g) (lambda (x) (f (g x)) )) C will let you return an *existing* function, but the standard contains no operations which can be used to create *NEW* functions at run time, and that is what was required here. The original poster wanted to be able to do things like typedef int intfn(int); intfn compose(intfn f, intfn g) { /* create a new function fg and return it */ } intfn a = compose(sqr, cube); intfn b = compose(a, a); intfn c = compose(b, iabs); On the machine I am using (an Encore Multimax) it was rather easy to implement compose() in C, but it involved -- filling a new block of memory with machine code -- casting function pointers to unsigned long -- casting (char *) to function pointer none of which operations is what you might call portable. The bottom line is that the operation *can* be implemented quite easily on many machines, without even leaving C for as much as an asm() statement, but that there is NO *portable* way of dynamically calculating a new *C* function in C. What's rather unsettling is the number of people who have completely misunderstood the question. -- The purpose of advertising is to destroy the freedom of the market.