Content deleted Content added
→Clarity: re |
|||
Line 735:
: Regarding your proposed lead sentence, a closure is not "a function which returns another function". If a functions ''wants'' to return a function it should probably return a closure instead (which is the function begin returned together with some extra data that make it possible for that returned to function to still have access to the variables contained in the returning function's scope.) Cheers, —''[[User:Ruud Koot|Ruud]]'' 19:34, 20 September 2011 (UTC)
:: I'm not sure I follow the examples, but are you just clarifying my lead by saying that a closure is when a function returns a function *while preserving scope*? If so, a closure sounds a bit like a class with a member function... --[[Special:Contributions/204.87.16.4|204.87.16.4]] ([[User talk:204.87.16.4|talk]]) 13:04, 21 September 2011 (UTC)
::: Basically, yes. When a function ''f'' wants to return a function ''g'' it should instead return a closure, which can be seen as a function pointer to ''g'' together with a bit of additional data that allows ''g'' to preserve its scope once it gets called.
::: The main difficulty that most people have when trying to understand closures is that a lot of popular languages like C, Java and C# 1.0 don't have nested functions and therefore no non-local variables (only local and global variables). So in those languages you generally don't need a closure, a function pointer is sufficient.
::: You can find a lot of discussion on the Internet on whether closures and objects are equivalent. While you can see closures as a simple kind of objects, I don't think that view is really helpful in understanding what closures are. You can do things with objects that you can't easily do with closures (have more than one member function, have public member variables, polymorphism, etc.) and things with closures that you can't easily do with objects (two closures can share the same "private member variable" and use it as a private communication channel, which objects can't directly any language I know.) There is a lot of literature on building object systems on top of closures and simulating closures using objects, but that isn't how they are primarily used in languages that support those features. —''[[User:Ruud Koot|Ruud]]'' 16:43, 21 September 2011 (UTC)
|