有没有办法在 C 中进行柯里化? [英] Is there a way to do currying in C?

查看:21
本文介绍了有没有办法在 C 中进行柯里化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个指向函数 _stack_push(stack* stk, void* el) 的指针.我希望能够调用 curry(_stack_push, my_stack) 并返回一个只需要 void* el 的函数.我想不出办法来做到这一点,因为 C 不允许运行时函数定义,但我知道这里有比我更聪明的人:).有什么想法吗?

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 function that just takes void* el. I couldn't think of a way to do it, since C doesn't allow runtime function definition, but I know there are far cleverer people than me here :). Any ideas?

推荐答案

我找到了 Laurent Dami 的一篇论文,讨论了 C/C++/Objective-C 中的柯里化:

I found a paper by Laurent Dami that discusses currying in C/C++/Objective-C:

使用柯里化函数在 C/C++/Objective-c 中实现更多功能可重用性

对它是如何在 C 中实现的感兴趣:

Of interest to how it is implemented in C:

我们当前的实现使用现有的 C 结构来添加柯里化机制.这比修改编译器容易得多,并且足以证明柯里化的兴趣.然而,这种方法有两个缺点.首先,柯里化函数不能进行类型检查,因此需要小心使用以避免错误.其次,curry 函数无法知道其参数的大小,并且将它们计算为一个整数的大小.

Our current implementation uses existing C constructs to add the currying mechanism. This was much easier to do than modifying the compiler, and is sufficient to prove the interest of currying. This approach has two drawbacks, however. First, curried functions cannot be type-checked, and therefore require careful use in order to avoid errors. Second, the curry function cannot know the size of its arguments, and counts them as if they were all of the size of an integer.

这篇论文没有包含 curry() 的实现,但是你可以想象它是如何使用 函数指针可变参数函数.

The paper does not contain an implementation of curry(), but you can imagine how it is implemented using function pointers and variadic functions.

这篇关于有没有办法在 C 中进行柯里化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆