Article View: comp.lang.misc
Article #2533Look, Ma, I can dynamically compose functions in C!
From: Dan Bernstein
Date: Fri, 21 Dec 1990 00:23
Date: Fri, 21 Dec 1990 00:23
70 lines
2297 bytes
2297 bytes
In article <1990Dec19.222059.6878@mathrt0.math.chalmers.se> augustss@cs.chalmers.se (Lennart Augustsson) writes:
> To see the difference just try to write a function
> that does function composition.
Okay. (What follows isn't tested but you'll get the idea.)
We'll work with a function descriptor type:
struct basicfun { int (*f)(); } ;
struct twofun { struct fun *first; struct fun *second; }
struct fun { int type;
union { struct basicfun b; struct twofun t; } u;
} ;
#define BASICTYPE 1
#define TWOTYPE 2
To convert a C function pointer into one of these things, given storage
space:
struct fun *cftofun(c,f)
int (*c)();
struct fun *f;
{
f->type = BASICTYPE;
f->u.b.f = c;
return f;
}
To call one of these things, given the argument:
int callfun(f,x)
struct fun *f;
int x;
{
switch(f->type)
{
case BASICTYPE: return f->u.b.f(x);
case TWOTYPE: return callfun(f->u.t.second,
callfun(f->u.t.first,x));
}
}
Finally, to answer the question:
struct fun *compose(second,first,f)
struct fun *second;
struct fun *first;
struct fun *f;
{
f->type = TWOTYPE;
f->u.t.first = first;
f->u.t.second = second;
return f;
}
Of course, a more complete implementation would manage struct fun
storage, possibly with garbage collection.
A different strategy is to store basic functions as just pointers, and
composed functions as a pointer to a special function, followed by the
first and second pointers; then pointers to these ``objects'' would be
passed in as arguments.
Back to Lennart:
> I claim that this is impossible to do in a portable way.
You were saying?
---Dan
Technical Details
Message-ID:
<19468:Dec2100:23:0790@kramden.acf.nyu.edu>Path:
arc1-ca.pugleaf.net!utzoo!attcan!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!hsdndev!cmcl2!kramden.acf.nyu.edu!brnstndReferences:
<20@garth.UUCP> <27534.276e5bd3@kuhub.cc.ukans.edu> <1990Dec19.222059.6878@mathrt0.math.chalmers.se>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!hsdndev!cmcl2!kramden.acf.nyu.edu!brnstnd From: brnstnd@kramden.acf.nyu.edu (Dan Bernstein) Newsgroups: comp.lang.misc Subject: Look, Ma, I can dynamically compose functions in C! Message-ID: <19468:Dec2100:23:0790@kramden.acf.nyu.edu> Date: 21 Dec 90 00:23:07 GMT References: <20@garth.UUCP> <27534.276e5bd3@kuhub.cc.ukans.edu> <1990Dec19.222059.6878@mathrt0.math.chalmers.se> Organization: IR Lines: 70 X-Original-Subject: Re: Complexity of syntax