I Need Closure
This morning I was reading in the new Pickaxe, mostly looking for tidbits of Ruby 1.9 glory.
On page 67 I found one of the best and most concise definitions of a closure.
For comparison, here's the first paragraph on closure from Wikipedia:
"In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Closures are used to implement continuation passing style, and in this manner, hide state. Constructs such as objects and control structures can thus be implemented with closures."
Wow there's a lot of links in there. Here's Dave Thomas' page 67 definition:
- closure
- variables in the surrounding scope that are referenced in a block remain accessible for the life of that block and the life of any Proc object created from that block.
It reminded me of something a college professor of mine said. That closures were like a sack that you threw a method and some variables into. You could carry that sack around and wherever you opened it, that method would use the variables in the sack.
He also said that electrons in a transistor were like putting a box of puppies in a corner.