Closures are an efficient way to implement functions.
I claim that every function is conceptually a closure, even in the few languages which don't have them.
The closed variables are then constants or static data inside the code. But in full-fledged closures (like in Ocaml, Scheme, Common Lisp, or C++11) the closed variables and the code are in the closure itself.
For instance, in C (and in C++98) functions are closures, but their closed (or free) variables are restricted to be static
or global variables.
Closures also brings the possibility for anonymous functions, e.g. lambdas, which create closures with new closed variables (and that is something not possible in standard C). This is the abstraction operation of the λ-calculus (which does not exist in C, this is why every callback function -e.g. in GTK- takes some "client data" as an extra parameter).
From an implementation point of view, a function is always some code with some data required by the code. The data are the closed variables. For compiled C code, the data is wired in the code as fixed global or static variables (and changing these variables require recompilation), or as literal constants. So the only way of making an abstraction would be to regenerate some new code with some new variables in it.
Abstraction does not exist in standard C because there is no way to generate portably new functions. But you could use weird implementation-specific tricks. Imagine that you want to implement the translation generator function. In ocaml, the function to generate the translated-by delta
function is
let transl delta = fun x -> x + delta
and that is generating a new closure for every invocation. So in
let t3 = transl 3 in t3 5
a new closure t3
is generated (but perhaps the optimizer is removing it) and the result is 8 (which is 3+5).
You could do insane tricks in C: on Linux, you would for example generate at runtime a new textual file t3mod.c
containing
int t3(int y) { return y+3; };
and you would compile that t3mod.c
file in a shared object t3mod.so
and dlopen
it then dlsym
it using "t3"
. This contrived way (using C code generation at runtime, then dynamically loading it) is a way of implementing abstractions in C and it is a way to generate dynamically new function pointers. Likewise, you might use JIT compiling libraries like e.g. libjit, LLVM (or libgccjit
in future GCC 5). Read also about partial evaluation & eval & multi-stage programming (e.g. Meta OCaml...). See also J.Pitrat's blog entries on meta-combinatorial search & meta-bugs.