Talk:First-class functions: Difference between revisions

(even C could?)
 
Line 10:
 
I bet classifiers say that C functions are not first class... And if you can write such code, this does not mean that the ''language'' has first-class functions... so all these theoretical classifications regard only the ''primitive'' syntax (or better semantics?) of a language...? Or could I try to ''cheat''? (Like I did for one-liner...!) --[[User:ShinTakezou|ShinTakezou]] 16:39, 24 February 2009 (UTC)
 
Yes, it's that last point that is crucial. In standard portable C, you can get a pointer to any function that was written in the original source code (of your program or a library), but there's no way to construct an arbitrary number of new functions.
 
You could simulate it by having a table and a set of functions referring to entries in it; but you would have to deal with allocating this limited resource. For example:
 
<lang c>typedef int (*ourfunc)(int);
 
ourfunc[4][2] composeData;
int freeRow = 0;
 
int compose_0(int x) { return composeData[0][0](composeData[0][1](x)); }
int compose_1(int x) { return composeData[1][0](composeData[1][1](x)); }
int compose_2(int x) { return composeData[2][0](composeData[2][1](x)); }
int compose_3(int x) { return composeData[3][0](composeData[3][1](x)); }
ourfunc functions[4] = {compose_0, compose_1, compose_2, compose_3};
 
ourfunc compose(ourfunc a, ourfunc b) {
composeData[freeRow][0] = a;
composeData[freeRow][1] = b;
return functions[freeRow++];
}</lang>
 
But this technique will only work for a fixed number of functions -- it is basically emulating closures by having a predefined table of closure entry points and data storage.
--[[User:Kevin Reid|Kevin Reid]] 17:54, 24 February 2009 (UTC)