在C中部分应用函数 [英] Partially applying a function in C
问题描述
我有以下代码:
/* Function that takes a list and applies "function" to every element */
struct list *iter(struct list *l, void (*function)(struct list *a));
我有一个函数 foo(arg1,arg2,struct list * a
,我想将其应用于列表中的每个元素.
And I have a function foo(arg1, arg2, struct list *a
that I want to apply to every element of my list.
如何实现这种行为?在支持闭包或循环的编程语言中,我将对 arg1
和 arg2
部分地应用 foo
,但是在C语言中似乎是不可能的.
How can I achieve such a behaviour ? In a programming language that supports closures or currying I would have partially applied foo
to arg1
and arg2
, but it seems to be impossible in C.
是否可以让函数返回指向函数的指针 bar(struct list * a)= foo(arg1,arg2,a)
吗?
Is it possible to have a function return a pointer to a function bar(struct list *a) = foo(arg1, arg2, a)
?
推荐答案
基于您的函数定义:
struct list *iter(struct list *l, void (*function)(struct list *a));
我假设您的列表由一系列 struct list
对象组成(与具有单独的Head和Node类型的列表相对).
I'm assuming that your list consists of a series of struct list
objects (as opposed to lists which have a separate Head and Node type).
要使回调更通用,您需要提供一个额外的参数,调用方可以根据自己的需要定制该参数:
To make the callback more generally usable, you need to supply an extra argument which the caller can tailor to their own needs:
struct list *iter( struct list *l, void *arg, void (*function)(void *, struct list *));
在 iter
中,使用 function(arg,l);
然后您以这种方式调用 foo
:
Then you invoke foo
this way:
struct foo_args { arg1_t arg1; arg2_t arg2; }; // at file scope
void handler(void *args, struct list *node) // at file scope
{
struct foo_args *p_args = args;
foo(p_args->arg1, p_args->arg2, node);
}
// in a function
struct foo_args args = { arg1, arg2 };
iter(l, &args, handler);
当前您不使用 function
的返回值,通常可以将其用作标志以指示迭代是否应中断(例如,由于处理此节点失败或发现了它的结果)正在寻找).
Currently you're not using function
's return value, typically this can be used for a flag to indicate whether the iteration should break (e.g. because processing this node failed, or it found what it was looking for).
这篇关于在C中部分应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!