Qua*_*nce 3 c lisp lambda functional-programming currying
考虑以S-expr表示法编写的以下代码段:
(lambda (x) (lambda (y) (+ x y)))
Run Code Online (Sandbox Code Playgroud)
或者在Javascript中:
function(x) { return function(y) { return x+y; }; }
Run Code Online (Sandbox Code Playgroud)
我怎么用C写这个?
这在C中很难做到,因为它依赖于闭包.使用C,你必须传递一个显式的上下文,所以你最终可能会得到这样的东西.
#include <stdio.h>
struct closure {
int saved_x;
int (*function)(struct closure, int);
};
int second_half_add(struct closure context, int y) {
return context.saved_x + y;
}
struct closure curried_add(int x) {
struct closure ret;
ret.saved_x = x;
ret.function = second_half_add;
return ret;
}
int main() {
struct closure context = curried_add(3);
printf("%d\n", context.function(context, 4));
}
Run Code Online (Sandbox Code Playgroud)
它真的很难看,你几乎失去了所有的好处,但它有可能
| 归档时间: |
|
| 查看次数: |
252 次 |
| 最近记录: |