Is there a way to do currying in C?

后端 未结 4 1900
情话喂你
情话喂你 2020-11-27 04:34

Say I have a pointer to a function _stack_push(stack* stk, void* el). I want to be able to call curry(_stack_push, my_stack) and get back a functio

4条回答
  •  被撕碎了的回忆
    2020-11-27 04:56

    GCC provides an extension for the definition of nested functions. Although this is not ISO standard C, this may be of some interest, since it enables to answer the question quite conveniently. In short, nested function can access the parent function local variables and pointers to them can be returned by the parent function as well.

    Here is a short, self-explanatory example:

    #include 
    
    typedef int (*two_var_func) (int, int);
    typedef int (*one_var_func) (int);
    
    int add_int (int a, int b) {
        return a+b;
    }
    
    one_var_func partial (two_var_func f, int a) {
        int g (int b) {
            return f (a, b);
        }
        return g;
    }
    
    int main (void) {
        int a = 1;
        int b = 2;
        printf ("%d\n", add_int (a, b));
        printf ("%d\n", partial (add_int, a) (b));
    }
    

    There is however a limitation to this construction. If you keep a pointer to the resulting function, as in

    one_var_func u = partial (add_int, a);
    

    the function call u(0) may result in an unexpected behaviour, as the variable a which u reads was destroyed just after partial terminated.

    See this section of GCC's documentation.

提交回复
热议问题