The Problem: Closures in Functional Programming
A closure is a function bundled together with references to its surrounding state (its lexical environment). This means a closure can access variables from the scope in which it was defined, even after that outer scope has finished executing.
Example (Conceptual, using JavaScript-like syntax for clarity):
function makeAdder(x) {
// x is a local variable in makeAdder's scope.
// In a simple stack-based system, x would live on makeAdder's stack frame.
function adder(y) {
// This inner function 'adder' is a closure.
// It "closes over" or "captures" the variable 'x' from its lexical environment (makeAdder).
return x + y;
}
return adder; // We return the inner function itself.
}
// 1. Call makeAdder:
let add5 = makeAdder(5);
// At this point, if we were *purely* stack-based:
// - makeAdder(5) would be called.
// - A stack frame for makeAdder would be created, containing x = 5.
// - makeAdder would return the 'adder' function.
// - makeAdder's stack frame would be POPPED. The memory for 'x' would be GONE.
// 2. Now, call the returned function:
let result = add5(10); // This should be 15
// BUT HOW?! If 'x' (which was 5) was on makeAdder's stack frame,
// and that stack frame is gone, how can 'add5' (which is 'adder')
// still access 'x' to calculate x + y?
Why a Simple Stack Fails Here:
- When
makeAdder(5) returns, its stack frame (which would contain x=5) is popped.
- If
x was only on the stack, it would be deallocated and gone.
- When
add5(10) (which is the adder function created inside makeAdder) is later called, it needs to access the value of x (which was 5).
- If
x is gone, add5 cannot function correctly.
The Dynamic Runtime / Garbage Collection Solution:
To solve this, FP languages (and others that support closures, like Python, JavaScript, Java with lambdas, C# with delegates/lambdas) do the following:
- Heap Allocation for Captured Variables: When the compiler/interpreter sees that a variable (
x in our example) is captured by a closure, it ensures that x is allocated on the heap instead of (or in addition to) the stack. The heap is a region of memory for dynamically allocated objects that can live beyond the scope of a single function call.
- Closure Contains References: The closure object (
adder) stores a reference (pointer) to the heap-allocated x.
- Garbage Collection: Because
x is on the heap, its lifetime is no longer tied to makeAdder's stack frame. It will persist as long as something (like the add5 closure) still has a reference to it. When add5 itself is no longer reachable (e.g., it goes out of scope and no other part of the program uses it), the garbage collector will eventually reclaim the memory for the closure object and the heap-allocated x (if nothing else references x).