4 ms·
Read the comments on the blog, actually a lot more insightful then his post
by hypermatt 17y ago
Read the comments on the blog, actually a lot more insightful then his post
- mustpax 17y agoI think the distinction between a lambda and a closure is especially important. Closures maintain references to the local stack and I shudder to think the kind of bugs and unsafe memory operations that can result to writing to bad places in the stack. Buffer overflows anyone?
- bitwize 17y agoNo. Closures, if implemented properly, may contain references to variables in the enclosing lexical environment where the closure was defined. Whether they live on the stack or in the heap is an implementation detail, and may have everything to do with the provable dynamic extent of the closure (e.g., downward funargs can point back onto the stack whereas upward funargs must be heap-allocated).
- cousin_it 17y agoIn 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.