Hacker News new | past | comments | ask | show | jobs | submit login

If x was a global variable then you don't have a closure, just an anonymous function.

Closures require closed over variables.




>Closures require closed over variables.

Is "over variables" a term here? Is that the same as "upvalues"?


Yup, the "upvalues" of a closure are the dependencies of the function that the closure "closes over".

So in OO terms, the reason "bar closes over x" is because bar's execution has a dependency on the value of x. Since bar needs x to execute, we "close bar over x (and whatever other dependencies bar has)" to create the "closure".

To demonstrate some other uses, when we take "the closure [of|over] bar", we "close over bar", meaning "find all of bar's dependencies, and bundle them". The resulting closure is "closed over x", as well. I guess in this context "over" means "including". So you've got a bunch of references and a function laying around. You take a "closure" like you would a tarp or something, and put it "over" all that stuff. Now you've got the function and the references "closed over" by the "closure".

Personally, I think this terminology is a little weird and immediately intuitive to someone without a math background [1]. On the other hand, getting good at comprehending less-than-intuitive definitions seems to be a big part of CS and Math, so it's important to get used to it :)

1. There are "closed" things are all over mathematics, meaning vaguely similar things: http://en.wikipedia.org/wiki/Closed


Your explanation here is very, very helpful. I just copied and pasted it into a file for later reference. Thank you for taking the time to explain this!


Cool! Glad to be helpful :) I feel like I'm rephrasing the same thing a lot, but in hindsight, closures took me quite a bit of repetition/rephrasing to wrap my mind around. To fully grok them, you really need to have a clear understanding of how scope and variable references work.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: