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

As an old joke (a ha-ha only serious joke) goes, closures are a poor man's object orientation, and object orientation is a poor man's closure. Going on the list of languages you have above I'll take it from the object orientation side of the argument. Object orientation works by binding functions to data; the data is persistent for this instance of the object (in the sense that the data remains available as long as the object does) and can be manipulated by the functions bound to that data. Closures on the other hand bind data to functions; so the function is always callable but the data is bound to this instance of the function. So you can have many instances of a function each with it's own data bound to it. In most languages that support closures functions are considered a "first class" data type; i.e. individual functions (and the data bound to them) can be passed just like variables (sometimes with caveats depending on the implementation). Typically this comes hand in hand with "anonymous" functions; functions that don't have an entry in the symbol table, i.e. they don't have a name in the function / object namespace.

If you truly want to understand how it works then you'd probably want to write a compiler that supports closures; you'd then need to cover issues like how to allocate functions on the heap, the difference between locally allocated (typically on the stack) data bound to functions and globally allocated (typically on the heap) data bound to functions.

The second part to closures is understanding the theory, or the why and the high level functionality that it enables, such as callbacks with state or interactions with the likes of recursive (y-combinator like) functions.

EDIT: minor grammar fix




Am I correct in my understanding that with a closure, it is one or more data bound to one function, while with object orientation, one or more functions are bound to one or more data?


Yes, but it can go a bit further.

http://c2.com/cgi/wiki?ClosuresAndObjectsAreEquivalent

A singular closure is 1+ data bound to an entity (function). A singular object is multiple data/functions bound to one entity (object).

In the link above there are examples of either generating multiple closures tied to the same set of data (like tel's example), and also examples of having a singular closure that takes as a first parameter a "method" name and branching based on that. Using either solution you have an OO system using closures as your basis.




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

Search: