函数式编程风格的前提是要有一等公民函数。如果你能接受以下内容,那么它可以在可移植的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));
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));
}
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
};
apply(increment, &(struct list_t) { number(1), NULL });
本质上,我们使用由功能/参数对以及一堆宏表示的闭包来模拟一等函数。完整的代码可以在这里找到。