C中的高阶函数作为一种语法糖,只需很少的努力

Xia*_*Jia 6 c compiler-construction higher-order-functions

我想用C语言实现高阶函数(HOF)作为语法糖,只需要很少的努力.例如,对于以下代码

function add(int x) {
  return int(int y) {
    return x + y;
  };
}

int main() {
  function add1 = add(1);
  return add1(2);
}
Run Code Online (Sandbox Code Playgroud)

它被转换成纯C作为

#include <stdlib.h>

typedef struct {
  void *ctx;
  void* (*fun)(void *arg, void *ctx);
} function;

function new_function(void *ctx, void* (*fun)(void *, void *)) {
  function f = {.ctx=ctx, .fun=fun};
  return f;
}

void* apply(function f, void *arg) {
  return (*(f.fun))(arg, f.ctx);
}

typedef struct {
  int x;
} context$1;

void* new_context$1(int x) {
  context$1 *ctx = malloc(sizeof(context$1));
  ctx->x = x;
  return ctx;
}

void* function$1(void *arg, void *ctx) {
  int y = (int)arg;
  int x = ((context$1*)ctx)->x;
  return (void*)(x + y);
}

function add(int x) {
  return new_function(new_context$1(x), function$1);
}

int main() {
  function add1 = add(1);
  return (int)apply(add1, (void*)2);
}
Run Code Online (Sandbox Code Playgroud)

我已经运行了这个(手动)转换版本,它运行正常.为了实现,我相信一些AST操作和lambda提升就足够了.

我的方法有任何潜在的缺陷吗?是否有更简单的HOF方法,或者我可以改进我的方法以使其更容易实现吗?

Ant*_*nko 2

目前有两个明显的问题:

  • 使用 void* 来表示任何类型的参数和返回值最终都会崩溃。考虑 ia-32 上的“long long”参数,或任何按值传递的结构。
  • 如果没有垃圾回收,很难(如果可能的话)使高阶函数变得有用。您可以从您自己的示例中看到,其中 context$1 已分配但从未释放。Boehm GC 在这里可能会有所帮助。