使用宏“高阶函数"在 C 中进行函数式编程发电机 [英] Functional programming in C with macro "Higher Order Function" generators
问题描述
请注意,因为这是一个地狱般的问题;-)
Pay attention carefully because this is a hell of a question ;-)
我想在 C 中将模板函数用于泛型集合操作(如搜索、foreach 等),同时保持编译器静态类型检查.当您使用像本例中这样的简单回调时,这是相当简单的:
I want to use template functions for generic collection actions (like search, foreach, etc.) in C while maintaining compiler static type checking. It is fairly straightforward while you're using simple callbacks like in this example:
#define MAKE_FOREACH(TYPE)
void foreach_##TYPE (TYPE[n] array, int n, void(*f)(TYPE)) {
for(int i = 0; i < n; i++) {
f(array[i]);
}
}
因此您可以执行以下操作:
so you can do things like:
MAKE_FOREACH(int)
MAKE_FOREACH(float)
void intcallback(int x){
printf("got %d
", x);
}
void floatcallback(float x){
printf("got %f
", x);
}
int main(){
int[5] iarray = {1,2,3,4,5};
float[5] farray = {1.0,2.0,3.0,4.0,5.0};
foreach_int(iarray, 5, intcallback);
foreach_float(farray, 5, floatcallback);
}
如果我想实现带有返回类型的回调,例如创建一个map"函数,我可以这样做:
If I'd like to implement callbacks with return types, for example to make a "map" function, I could do:
#define MAKE_MAP(TYPE, RTYPE)
RTYPE* map_##TYPE (TYPE[n] array, int n, RTYPE(*f)(TYPE)) {
RTYPE* result = (RTYPE*)malloc(sizeof(RTYPE)*n);
for(int i = 0; i < n; i++) {
result[i]=f(array[i]);
}
}
到目前为止,一切都很好.现在问题来了,当我希望我的回调函数接受任意数量的类型参数时.
So far, so good. The problem comes now, when I want my callback functions to accept any number of typed arguments.
这个想法是这样的:
#define MAKE_MAP(TYPE, RTYPE, ...)
RTYPE* map_##TYPE (TYPE[n] array, int n, RTYPE(*f)(TYPE, __VA_ARGS__), __VA_ARGS__)
/*this would work for the declaration (because just the types would be enough)
but the parameter names are missing :-s*/
{
RTYPE* result = (RTYPE*)malloc(sizeof(RTYPE)*n);
for(int i = 0; i < n; i++) {
result[i]=f(array[i], /*here the names of the parameters, in order*/);
}
}
所以,如你所见,我可以声明一个地图函数:
so, as you can see, I could declare a map function as:
MAKE_MAP(int, float, char)
给予:
float* map_int(int[n] array, int n, float(*f)(int, char), char);
但我无法弄清楚如何实现通过预处理器传递的参数.我在这里寻求您的帮助、想法和建议.
but I cannot figure how to implement the parameter passing with the preprocessor. Here is where I ask for your help, ideas and suggestions.
(顺便说一句,不要告诉我使用可变参数函数作为模板并将 va_list 参数传递给回调,因为所有这些都是因为类型检查:-p)
(By the way, don't tell me to use a variadic function as template and passing a va_list argument to the callback, because all this stuff was because of the type checking :-p)
推荐答案
如果您使用的是 Linux/BSD Unix,请查看 queue(3) 并检查 /usr/include/sys/queue.h
- 之前已经完成了 :)
If you are on Linux/BSD Unix, take a look at queue(3) and check into /usr/include/sys/queue.h
- it's been done before :)
这篇关于使用宏“高阶函数"在 C 中进行函数式编程发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!