Search code examples
cfunctional-programming

What tools are there for functional programming in 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.

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.

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.

[Edit] 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.


Solution

  • 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.

    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).