2 ms·
In lambda calculus, where the term "lambda" comes from, lambda expressions can close over free variables. http://en.wikipedia.org/wiki/Lambda_expression http://
by cousin_it 17y ago
In lambda calculus, where the term "lambda" comes from, lambda expressions can close over free variables. http://en.wikipedia.org/wiki/Lambda_expression http://en.wikipedia.org/wiki/Lambda_expression
I think about it as a three-way distinction rather than dichotomy. Here goes:
1) Anonymous functions that don't close over variables in their scope. Example: summing a list by passing "plus" to "fold". Doesn't require much runtime support beyond C, only a syntactic extension.
2) Anonymous functions that close over their environment but can only be passed down the stack - "downward funargs". Example: enveloping calls, like Ruby's File#open. Basically we encapsulate file I/O in a function that works thus: open the file, pass the file descriptor to an anonymous function received as argument, then after it completes work (or upon any exception) close the file.
3) Full closures that can outlive the context they were created in. Example: an event handler that we attach to a button in JavaScript. This case often requires that stack frames reside on the heap and be subject to garbage collection.
Re buffer overflows: if the language support is implemented properly, a closure created in a certain scope has exactly the same potential for buffer overflows etc. as regular code executed in that scope. EDIT: see the comment by limmeau nearby.