5

Wikipedia says, that closure - is a function, which has an access to variables, declared outside of the function. There is even an example:

function startAt(x)
   function incrementBy(y)
       return x + y
   return incrementBy

variable closure1 = startAt(1)
variable closure2 = startAt(5)

But according to most programming languages (including python, javascript, swift, etc.) the next example is correct (written in python):

# Script starts
test = "check"

def func(test2):

    def func2():
        return test2 == test

    return func2()

print func("check") // returns TRUE
# Script ends

Basically, func is not a closure, but it obviously uses variable test, declared outside of the function. Does that mean func IS a closure?

Even in C++ you can run this:

std::string test = "check";

bool func(std::string test2) {
    if (test2 == test)
        return true;
    else
        return false;
}

int main() {
    if (func("check"))
        std::cout << "TRUE" << std::endl; // prints TRUE
}

Eventually, this makes every function being a closure. Where am I wrong?

  • 9
    For the C++ example, globals/static variables don't count. The property of interest closures have is that they can refer to temporary, scoped variables. – Doval Nov 17 '14 at 20:20
  • @Doval: In other words, instance methods are closures, while static methods or functions are not? – Gabe Nov 18 '14 at 4:24
  • 1
    @Gabe I wouldn't say so, because the user of the method has to have a reference of some sort to the object, whereas with a closure that detail is opaque to the user and it just behaves as a function. – chbaker0 Nov 18 '14 at 6:57
  • 1
    @Gabe Conceptually, they behave the same, but that's generally not what people mean when they talk about closures either. Closures are about capturing local variables. That's an interesting thing because which local variables get captured depends entirely on what code executes. This is why I said globals/static variables don't count - their location is statically known (i.e. at compile time). Likewise, for a given class it's also statically known which instance fields a method can access. – Doval Nov 18 '14 at 12:24
  • @mebob: So a C++ method isn't a closure, but a C# method is because it can be automatically turned into a delegate, and a delegate with a target object is a closure? – Gabe Nov 18 '14 at 13:43
25

No, not every function is a closure.

Wikipedia says:

... closure ... is a function or reference to a function together with a referencing environment — a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

I'd add "non-local and non-global", but the idea is correct.


Neither your C++ nor Python examples use closures. In both cases it's just scoping rules allow functions to see their outer scope and global scope.


"Closure" happens in the 1st example - incrementBy is constructed in and then returned from it's outer function, capturing argument x. When you assign variable closure1 = startAt(1), you end up having a closure (function) inside closure1 var which captured argument, which value happened to be 1, so when you call closure1(2) the result is 3 (1 + 2).

Think of it as memorizing some information about closure's declaration scope: incrementBy retain a memory about insides of startAt, specifically a value of it's argument x.

In lambda calculus, as I know, those "non-local" variables are called "free", and functions with free variables are called "open terms". Closure is a process of "closing" open terms by "fixing" values of those free variables in aforementioned "environment table". Hence the name.


It's worth noting that in Python and JS closure happens implicitly, while in PHP you have to explicitly tell which variables you want to close over (capture): http://php.net/manual/en/functions.anonymous.php - note use keyword in declarations:

// equivalent to the 1st example
function startAt($x) { //        vvvvvvvv          vv
    $incrementBy = function ($y) use ($x) { return $x + $y };
    return $incrementBy;
}
  • Thank you, it's a great answer. Looks like I've lost in the terminology. But, looking back to my python example, can't we say, that func, which is being constructed in the global scope, captures variable test as incrementBy does? – Hast Nov 17 '14 at 21:01
  • 4
    No, because test is global - it is visible from anywhere, unless "shadowed" by some local variable with the same name. Also, and it's more important, it remains it's existence after func execution is over. On the other hand, when startAt execution is over, x would be gone forever if it wouldn't be captured by incrementBy. Capturing "saves" x from garbage collection. – scriptin Nov 17 '14 at 21:05
  • Also, don't worry about lambda calculus terminology - it is not required to use closures properly. – scriptin Nov 17 '14 at 21:07
  • @scriptin test2 in the Python example isn't a global, though, and is used from the inner function. – Aleksi Torhamo Nov 19 '14 at 6:43
  • 1
    @AleksiTorhamo yes, but it is used right away (return func2()) in the same scope where it is directly visible, so it isn't captured – scriptin Nov 19 '14 at 18:52
4

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.

  • "Closures are an efficient way to implement functions." What makes you say that? A closure is generally a function plus an environment pointer, so either your implementation is recursive (if you implement the function in the closure as a closure), or it is not optimally efficient (since the function inside the closure has less overhead than the closure itself). – Sebastian Redl Nov 18 '14 at 14:16
  • "I claim that every function is conceptually a closure" While you can argue that a standalone function is a closure with an empty environment, doing so makes the term "closure" useless. – Sebastian Redl Nov 18 '14 at 14:17
  • The important word is conceptually – Basile Starynkevitch Nov 18 '14 at 14:22
  • Your compiled C code contains an environment, as static or global variables. – Basile Starynkevitch Nov 18 '14 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.