函数式编程风格的先决条件是一流的函数。如果你容忍下一个,它可以在便携式 C 中模拟:
- 词法范围绑定的手动管理,也就是闭包。
- 手动管理函数变量的生命周期。
- 函数应用程序/调用的替代语法。
/*
* with constraints desribed above we could have
* good approximation of FP style in plain C
*/
int increment_int(int x) {
return x + 1;
}
WRAP_PLAIN_FUNCTION_TO_FIRST_CLASS(increment, increment_int);
map(increment, list(number(0), number(1)); // --> list(1, 2)
/* composition of first class function is also possible */
function_t* computation = compose(
increment,
increment,
increment
);
*(int*) call(computation, number(1)) == 4;
此类代码的运行时可能小到以下
struct list_t {
void* head;
struct list_t* tail;
};
struct function_t {
void* (*thunk)(list_t*);
struct list_t* arguments;
}
void* apply(struct function_t* fn, struct list_t* arguments) {
return fn->thunk(concat(fn->arguments, arguments));
}
/* expansion of WRAP_PLAIN_FUNCTION_TO_FIRST_CLASS */
void* increment_thunk(struct list_t* arguments) {
int x_arg = *(int*) arguments->head;
int value = increment_int(x_arg);
int* number = malloc(sizeof *number);
return number ? (*number = value, number) : NULL;
}
struct function_t* increment = &(struct function_t) {
increment_thunk,
NULL
};
/* call(increment, number(1)) expands to */
apply(increment, &(struct list_t) { number(1), NULL });
本质上,我们模仿了第一类函数,闭包表示为一对函数/参数加上一堆宏。完整的代码可以在这里找到。