函数式编程风格的前提是一流的功能。如果您愿意,可以在便携式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 });
从本质上讲,我们模仿的是一流的函数,其闭包表示为一对函数/自变量加一堆宏。完整的代码可以在这里找到。