function composition in C

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Fri Mar 1 17:42:56 AEST 1991


In article <ACHA.91Feb28002548 at DRAVIDO.CS.CMU.EDU>, acha at CS.CMU.EDU (Anurag Acharya) writes:
> 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.

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.



More information about the Comp.lang.c mailing list