问题描述
我最近一直在想了很多关于如何去用C做函数式编程(的不的C ++)。很显然,C是一个程序语言,并没有真正支持函数式编程本身。
I've been thinking a lot lately about how to go about doing functional programming in C (not C++). Obviously, C is a procedural language and doesn't really support functional programming natively.
是否有任何的编译器/语言扩展,一些功能的编程结构添加到语言? GCC提供中作为语言的扩展。嵌套函数可以从父栈帧访问变量,但是这仍然是一个很长的路离成熟关闭。
Are there any compiler/language extensions that add some functional programming constructs to the language? GCC provides nested functions as a language extension; nested functions can access variables from the parent stack frame, but this is still a long way away from mature closures.
例如,有一件事,我认为可以用C真正有用的是,任何地方的函数指针的预期,你可以能够通过一个Lambda前pression,创造一个封闭而衰变成一个函数指针。的C ++ 0x是要包括拉姆达前pressions(我认为这是真棒);然而,我在寻找适用于传统的C工具。
For example, one thing that I think could be really useful in C is that anywhere where a function pointer is expected, you could be able to pass a lambda expression, creating a closure which decays into a function pointer. C++0x is going to include lambda expressions (which I think is awesome); however, I'm looking for tools applicable to straight C.
为了澄清,我不是试图解决在C,它会更适合于函数式编程的一个特殊问题;我只是好奇,什么工具都在那里,如果我想这样做。
To clarify, I'm not trying to solve a particular problem in C that would be more suited to functional programming; I'm merely curious about what tools are out there if I wanted to do so.
推荐答案
让您建立封闭用C - 回调= alloc_callback(安培;功能,数据)
返回一个函数指针,这样回调(ARG1,...)
等同于调用功能(数据,ARG1,...)
。你将不得不手动处理垃圾收集,虽然。
FFCALL lets you build closures in C -- callback = alloc_callback(&function, data)
returns a function pointer such that callback(arg1, ...)
is equivalent to calling function(data, arg1, ...)
. You will have to handle garbage collection manually, though.
与此相关的已被添加到GCC苹果的叉块;他们不是函数指针,但他们让你绕过lambda表达式,同时避免了需要建立和手动捕获变量(实际上,一些复制和引用计数发生,背后隐藏着一些语法糖和运行时库)免费存储空间。
Relatedly, blocks have been added to Apple's fork of GCC; they're not function pointers, but they let you pass around lambdas while avoiding the need to build and free storage for captured variables by hand (effectively, some copying and reference counting happens, hidden behind some syntactic sugar and runtime libraries).
这篇关于是什么样的工具有在C函数式编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!