Content deleted Content added
m Maintain {{WPBS}}: 2 WikiProject templates. Keep majority rating "C" in {{WPBS}}. Remove 2 same ratings as {{WPBS}} in {{WikiProject Computer science}}, {{WikiProject Computing}}. Tag: |
|||
(95 intermediate revisions by 50 users not shown) | |||
Line 1:
{{Skiptotoctalk}}
{{WikiProject banner shell|class=C|1=
{{WikiProject Computer science |importance=Mid}}
{{WikiProject Computing |importance=Low |software=y |software-importance=Mid}}
}}
{{To do}}
==Don't start with Lisp==
I don't think the initial examples should be in Lisp. Here's why: the vast majority of Lisp programmer will already be familiar with closures, but a lot of people who navigate to this page will tend to be people who aren't familiar with Lisp (if they were familiar with Lisp, they'd probably know what a closure was already). I'd suggest (for the initial examples) some language which has syntax which is more C-like. Maybe javascript? Or maybe pseudocode. Of course, definitely include the Lisp code later. Just not the very first thing. Does anyone else agree?
Line 30 ⟶ 37:
This isn't right. In perl6 blocks will technically be closures, but thats pretty obscure stuff afaik. In perl5 blocks aren't closures. [[User:Demerphq|Demerphq]] 19:09, 7 April 2006 (UTC)
Scope != closure. A scope is an environment where you can get at a particular value via a particular variable name; a closure is a coderef that remembers the lexical scope where it was born. A lexical scope arises every time execution passes into a given block (or file), but you don't create a closure (at least in Perl 5) until you take a reference to a function that uses a lexical from its environment. That function has to be able to see that lexical in order to run, so the coderef has to wrap up (a piece of) the current lexical scope along with the function. It is this wrapping of state with functionality that makes a closure. (Which is more general than objects: You can take two or more coderefs that close over the same variable, if you want.) [[User:Eritain|eritain]] ([[User talk:Eritain|talk]]) 07:27, 26 October 2010 (UTC)
Regarding the "acts as an object" comment, I was thinking of a closure like this:
Line 86 ⟶ 95:
[[user:bjt|bjt]]
That's a scope, but I'd hesitate to call it a closure. The distinctive thing about closures is that you can (potentially) take multiple references to the same sub, and get it wrapped up with a different environment each time. In this example, we know from compile time that there is one and only one %cache, so no matter how many times I say \&fib there is never a need to clarify which %cache we mean, and therefore no reason to wrap any environment with the coderef. [[User:Eritain|eritain]] ([[User talk:Eritain|talk]]) 07:27, 26 October 2010 (UTC)
----
IMO the example ''was'' too complex. Also, Perl is a heinous language for explaining computer science concepts (e.g., you have to use "shift" to peel off arguments --- utterly obscure --- not to mention all the other random syntactic noise that comes with Perl). I replaced it with a more basic explanation that just conveys the idea of lexical scope capture. I used ML, which has a far more concise and pseudocode-like syntax than Perl.
Line 96 ⟶ 107:
----
Im going to add a perl example back to the page unless somebody protests. [[User:Demerphq|Demerphq]] 17:05, 10 April 2006 (UTC)
Seriously? no mention at all of Perl in the article?
[[Special:Contributions/159.83.196.1|159.83.196.1]] ([[User talk:159.83.196.1|talk]]) 18:30, 14 May 2018 (UTC)
==Closures and Java==
Line 102 ⟶ 115:
--[[User:Jwal|Jwal]] 18:35, 12 Jun 2004 (UTC)
Java has no first class functions, therefore has no closures.
Actually that java example on the anonymous class is overcomplicated for its result. The following code performs the same function without the need of creating an embedded runnable class. This is because the embedded Runnable classes run method is just called from the Thread classes run. Anyone who does threading in java knows this, which is why we can just extend thread instead of implementing Runnable. In such a case as this, it would be better formed code to just extend the thread into an anonymous, instead of creating an embedded runnable.
<syntaxhighlight lang="java">
class CalculationWindow extends JFrame {
private volatile int result;
...
public void calculateInSeparateThread(final URI uri) {
// The expression "new Thread() { ... }" is an anonymous class.
new Thread() {
public void run() {
// It can read final local variables:
calculate(uri);
// It can access private fields of the enclosing class:
result = result + 10;
}
}.start();
}
}
</syntaxhighlight>
[[Special:Contributions/76.235.207.239|76.235.207.239]] ([[User talk:76.235.207.239|talk]]) 09:11, 29 May 2011 (UTC)
Scala compiles to Java and supports Clousures. Not sure if this is an imperative language or not, but if so please append Scala to the list of "modern garbage-collected imperative languages support closures" <small><span class="autosigned">— Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[User:Jcalfee|Jcalfee]] ([[User talk:Jcalfee|talk]] • [[Special:Contributions/Jcalfee|contribs]]) 16:47, 22 August 2013 (UTC)</span></small><!-- Template:Unsigned --> <!--Autosigned by SineBot-->
==Closures and Python==
Python does not have closures and shouldn't even be listed among the list of languages that do have closures, let alone used as the example language to demonstrate what they are. Using Python to demonstrate what closures are is completely misleading and damaging to a reader's understanding of what closures are. Can we just swap the example language and remove Python from the list? <small><span class="autosigned">— Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[User:Mmachenry|Mmachenry]] ([[User talk:Mmachenry|talk]] • [[Special:Contributions/Mmachenry|contribs]]) 06:14, 25 June 2014 (UTC)</span></small><!-- Template:Unsigned --> <!--Autosigned by SineBot-->
Why Python doesn't have closures:
Line 153 ⟶ 192:
::What a silly remark is that! Why does the importance of a topic "not concern" you? Closures are an immensely important aspect of computer science, and they have '''nothing''' in common with function objects. The very minute the page on closures loses its page, I will make a new one. [[User:Wlievens|Wouter Lievens]] 09:05, 8 Jun 2005 (UTC)
::"it is not clear to me the difference between the two". Bully for you. But your ignorance and lack of perspicuity is no reason to merge articles about different topics. Rather, it suggests you shouldn't be editing such articles (or perhaps any articles).
:Because if a closure is not an obscure topic (which it is not), we still have to cover it. I am not saying this is not important so we have to merge it with the other. It's about overlap. For example, the example given in this article resembles the idea of a function object. -- [[User:TakuyaMurata|Taku]] 09:18, Jun 8, 2005 (UTC)
Line 159 ⟶ 200:
::From my point of view, keeping Closure as its own topic is useful from a searching perspective. I'm realatively new to computer science concepts, and when I came across 'closure' repeatedly in literature (and without a definition), a search on Wikipedia was immediately successful. If you don't already '''know''' that a closure is related to a [[function object]], it would be a bit harder to find. The articles should definitely reference each other; something like "A closure is very similar in most respects to a [[function object]]" in this article, and "Function objects are related to the more general concept of a [[Closure (computer science)|closure]]" in the other. From what I can tell of those to articles, they are separate (though related) things, and seem to deserve separate treatment. [[User:Radiantmatrix|RadiantMatrix]] 20:27, 23 Jun 2005 (UTC)
:: "the example given in this article resembles the idea of a function object" -- just because function objects (which, being objects encapsulate state) and closures (which implicitly capture the values of lexically scoped variables) have overlapping application doesn't mean they are the same thing. Sheesh. -- [[Special:Contributions/98.108.203.136|98.108.203.136]] ([[User talk:98.108.203.136|talk]]) 07:57, 20 June 2008 (UTC)
:My concepts of function objects and closure are those put in each article.
Line 184 ⟶ 227:
:::Another reason why these can't be merged, is because of terminology tradition. Your average C++ or Java programmer has ''never'' even heard of a closure, whereas the average Scheme/Lisp/ML programmer will think function object is a contradiction in terminis. [[User:Wlievens|Wouter Lievens]] 10:01, 22 Jun 2005 (UTC)
:"Maybe I am missing something" -- yes, the capacity to understand. -- [[Special:Contributions/98.108.203.136|98.108.203.136]] ([[User talk:98.108.203.136|talk]]) 07:57, 20 June 2008 (UTC)
:All right. I am convinced. If not merger, we at least mention how the two differ somehow. -- [[User:TakuyaMurata|Taku]] July 5, 2005 01:31 (UTC)
Line 352 ⟶ 397:
::::::: That was precisely what I meant when I wrote about "a function in JavaScript that can be used the same way Scheme's <code>if</code> or <code>cond</code> expression can be used".
::::::: It should be noted that you're effectively doing the same thing from the other end, by restricting your clients to a subset of the language when writing closures, by not giving them the same convenience they get when writing top-level methods (since they cannot return from the middle of the closure to the outer scope anymore). This stems from the fact that closures are simply not the right tool for the job - what you need to emulate control structures is blocks, [http://innig.net/software/ruby/closures-in-ruby.rb Ruby-style]. That way you get a structure which does not "rebind" return and other similar keywords from the outer scope, but that cannot outlive the scope it was created in either (so there's no possibility that it will be called when there's nothing to return from anymore), thus not a true closure. Well, in Ruby you can cheat your way around it, but at least you have to do that explicitly (by <code>proc</code>'ifying the block to an object). [[User:Int19h|-- int19h]] 05:39, 30 January 2007 (UTC)
::::::: The above JavaScript example is broken--it calls <code>ifcond()</code> twice, which if <code>ifcond()</code> alters any variables or calls any functions that alter anything, could result in incorrect state. Additionally, if something changes such that the second call to <code>ifcond()</code> does not return the same result as the first, both (or neither) of <code>ifblock()</code> and <code>elseblock()</code> could be evaluated. <small><span class="autosigned">—Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[User:Evildeathmath|Evildeathmath]] ([[User talk:Evildeathmath|talk]] • [[Special:Contributions/Evildeathmath|contribs]]) 16:54, 17 December 2008 (UTC)</span></small><!-- Template:Unsigned --> <!--Autosigned by SineBot-->
::::: I would certainly like it if I could write my own control flow structures in JavaScript as I used to do in FORTH. But you won't convince me, or any other experienced JavaScript programmer, that the language lacks closures. Ain't gonna happen. Sorry! :-) I've often heard the phrase "dictionaries are descriptive, not prescriptive." Doesn't the same principle apply to encyclopedias? --[[User:Geary|Michael Geary]] 08:13, 29 January 2007 (UTC)
Sidestepping the above the theoretical arguments real quick, I must say that I find the ECMAscript examples to be very illuminating, more so than the scheme/list ones (which are important in their own right of course). Regardless of whether the ECMA examples are "pure" in the language design sense, they definitely help bridge the gap for those used to procedural languages. Bravo to whomever put them in. [[User:Pkcirtap|Pkcirtap]] 00:44, 8 March 2007 (UTC)
I'm still fuzzy on what a closure is, and I too liked the EcmaScript examples, but I have a very minor beef with one of them. The first example in the [[Closure_(computer_science)#Differences_in_semantics|Differences in semantics]] section confused for an instant. I had read the x = 0 assignment, and I didn't notice the later x =1 assignment. Now, I now this is extremely minor, but I think the readability of the example increases if the initial assignment is x = 1. It seems a bit odd that its done the way it is, and rather than assume that its for no reason, I will assume that maybe I don't understand the reason. That, and my low level of understanding of the topic, keep me from editing myself. Hopefully one of the authors will read this and do the edit or explain the reasons to me (apparently I also need things to be typed slowly &8-P). [[User:Apwith|Apwith]] ([[User talk:Apwith|talk]]) 19:29, 16 October 2009 (UTC)
I believe that putting JavaScript examples to illustrate closures is confusing at best. Whatever this article has to say on this matter is questionable. I'm not trying to convince anyone that closures do not exist in JavaScript, but I believe that whenever you are trying to emulate them you are misusing the tool. What you call functions in JavaScript are not the first order functions, they are objects with context and properties. Of course you can say it is not a requirement for the closure to not have either of these, but, normally, you don't want to have them in closure. Besides, the examples given are in general an ill-suggested practice. This is because of how the runtime is implemented and, as I've said, it's just a wrong tool / improper use - it is never a requirement in JS to use this approach, and the alternative approach would always win in terms of code readability and performance. It looks more like if someone wanted very much that closures existed in JS, and some popular libraries, like JQuery or the Closure JS "compiler", make it look like it is there, but, I think we are dealing with the case of where the term is being used improperly to describe something similar, yet not exactly the same. (The need for closures in JS is probably because of wanting to make the code shorter overall, and it is due to the nature of JS - because it should load in the least possible time).<br>
Additionally, earlier on this page I've noted some C# programmer confusion created by Lisp examples, which is understandable, however, it is also strange that JavaScript was suggested as a better illustration, whilst closures are definitely possible in C#, which isn't a less popular language.<br>
[[User:Wvxvw|Wvxvw]] ([[User talk:Wvxvw|talk]]) 20:12, 12 May 2010 (UTC)
== What Are Closures ==
Line 530 ⟶ 583:
--[[User:Fubar Obfusco|FOo]] 07:36, 16 April 2007 (UTC)
Ok, i don't really know much about closures, but it seems to me that this sentence is not referring to private variables, but to static ones:
::A closure can be used to associate a function with a set of "private" variables, which persist over several invocations of the function.
Can you tell I was raised on OO? <small>—Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[Special:Contributions/206.83.243.126|206.83.243.126]] ([[User talk:206.83.243.126|talk]]) 20:28, 25 June 2008 (UTC)</small><!-- Template:UnsignedIP --> <!--Autosigned by SineBot-->
:Closures cannot be realized using static variables, which would be shared by all instances of the function. Every instance of the function has its own copy of the lexically scoped variables. — [[User:Tobias Bergemann|Tobias Bergemann]] ([[User talk:Tobias Bergemann|talk]]) 07:13, 26 June 2008 (UTC)
That metaphor about closures connected with space and time is totally useless and just confuses more the issue.
== Relate concept to broader semantics of "closure"? ==
Line 538 ⟶ 599:
: Via [http://lua-users.org/lists/lua-l/2004-11/msg00219.html this discussion]: <blockquote>The reason it is called a "closure" is that an expression containing free variables is called an "open" expression, and by associating to it the bindings of its free variables, you close it.<p>—Ake Wikstrom, ''Functional Programming using Standard ML''</blockquote>
: (Maybe this would make a good addition to the article?) --[[User:Piet Delport|Piet Delport]] 08:10, 27 May 2007 (UTC)
== Link farm ==
Line 543 ⟶ 606:
There are way too many external references at bottom, listing most everyone's blog entry on "How to do closures in language X (and what are they)". While a user of language X might want to know this, we should not try to anticipate every new programmer of every language. They can use Google, or one of the sites intended as indexes of PL resources, for that.
Absent strong objections, I'll remove about 80% of the external links pretty soon.
I agree. Only the links relevant to closures as such should remain, IMO. To be honest, I'd rather get rid of all the "how to do it in language XXX" sections in the article itself as well. [[User:Int19h|-- int19h]] 04:52, 23 July 2007 (UTC)
Line 549 ⟶ 612:
Firmly agreed, to both. "[[WP:NOT#HOWTO|How to]]" sections have strong tendency to accrete more and more languages, as visitors notice their favored ones are missing. (Look at the state the {{querylink|Currying|qs=oldid=142061535}} article was in recently.) —[[User:Piet Delport|Piet Delport]] 01:39, 24 July 2007 (UTC)
:I'm definitely in favor of also killing the "how to do it in language X" sections. Does someone else want to do that? I'd feel like I was overstepping slightly since all I've done in this particular article is delete the linkfarm.
== Closures and Objects ==
Line 555 ⟶ 618:
I don't believe the cited article, taken in context, supports the statement that closures are a better alternative to objects. It seems to say, instead, that closures and objects each have their appropriate place. If there are no objections, I will remove the second half of the following statement: "Closures can be used to implement object systems [2], and may in fact be better alternatives to objects [3]."
--[[User:Akellymi|Akellymi]] ([[User talk:Akellymi|talk]]) 16:09, 19 February 2008 (UTC)
==Etomology==
I'm trying to figure out what the etomology of the word "closure" is in this context. Is this a Lisp started term? --[[User:RobertGary1|RobertGary1]] ([[User talk:RobertGary1|talk]]) 23:12, 4 September 2008 (UTC)
: See [[#Relate concept to broader semantics of "closure"?|above]]. <span style="white-space:nowrap">—[[User:Piet Delport|Piet Delport]] <small>2009-08-25 08:32</small></span>
: (I went ahead and added an [[Closure (computer science)#Etymology|Etymology section]] to the article. <span style="white-space:nowrap">—[[User:Piet Delport|Piet Delport]] <small>2009-08-25 18:36</small></span>)
== lexical enclosure ==
What is a lexical enclosure? It should be mentioned in this article. [[User:Fresheneesz|Fresheneesz]] ([[User talk:Fresheneesz|talk]]) 18:42, 28 October 2008 (UTC)
== Free variables. ==
I think a small blurb about free variables is warranted. The linked article heavily concerns mathematical free variables and only has one small out of the way line saying "oh by the way free variables in computer science are references to non local variables" and that line even has a citation needed marking. My brain somehow parsed over that line and left me confused on the definition of closures for hours. [[Special:Contributions/75.23.252.148|75.23.252.148]] ([[User talk:75.23.252.148|talk]]) 02:40, 8 July 2009 (UTC)
== Example bloat ==
I removed the majority of the ''"in language x"'' examples from the article ({{diff|Closure (computer science)|prev|309942281|diff}}). As a rule of thumb, at most one example (in either Scheme or JavaScript, as per earlier consensus?) should be sufficient to illustrate any given concept: repeating it in everyone's favorite programming language just clutters the article. <span style="white-space:nowrap">—[[User:Piet Delport|Piet Delport]] <small>2009-08-25 10:57</small></span>
== Small typo? (not sure) ==
In the "Implementation and theory" section a sentence begins "In function languages with immutable data (like Erlang),...". Shouldn't this begin with "In function''al'' languages with immutable data (like Erlang),..."? Or am I misunderstanding, and it is correctly missing the "al"? Whoever reads this and knows, please feel free to update it if necessary, as I don't know the subject very well. --[[User:Donkeydonkeydonkeydonkey|Donkeydonkeydonkeydonkey]] ([[User talk:Donkeydonkeydonkeydonkey|talk]]) 19:56, 23 July 2010 (UTC)
: Yup, tyop, fixed it, thanks. - [[User talk:2over0|2/0]] <small>([[Special:Contributions/2over0|cont.]])</small> 00:11, 24 July 2010 (UTC)
== Closures in Objective-C ==
The example given is an example of closures in C, as amended by Apple's additions to the C language, and currently under review for inclusion in the C standard. It works in pure .c files under the gcc and clang, at least on Apple platforms. The only lines in the example that use Objective-C are the NSLog statements, which could be replaced with printf statements to have a pure C closure example. It is worth renaming (and repositioning up higher) the section "Closures in C (gcc, clang)" or somesuch. <small><span class="autosigned">—Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[User:Hyperjeff|Hyperjeff]] ([[User talk:Hyperjeff|talk]] • [[Special:Contributions/Hyperjeff|contribs]]) 09:23, 18 September 2010 (UTC)</span></small><!-- Template:Unsigned --> <!--Autosigned by SineBot-->
:I've expanded the section to refer to the fact it also applies to C and C++ in Mac. I don't think its should be moved higher or listed under C as it is a non-standard apple only extension.--[[User:Salix alba|Salix]] ([[User talk:Salix alba|talk]]): 10:04, 18 September 2010 (UTC)
== Definition of closure (the current one is awful...) ==
I think that the complicated definition of closure in current version [http://en.wikipedia.org/w/index.php?title=Closure_%28computer_science%29&oldid=421702686] is not explanatory, hardly understandable and must be improved. Please don't get me wrong, I do not question the correctness of the definition. It may be technically 100% right. The problem is that it does not really explains but confuses those who check Wikipedia while trying to understand what a closure is. Simply [http://www.google.com/search?q=Closure+explained google for "closure explained"], and you'll find some articles and blog posts saying more or less the same about Wikipedia's definition [http://www.codethinked.com/c-closures-explained] [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/] [http://tomasz.sterna.tv/2008/09/closures-explained/].
I suggest to move most of the first sentences down, and to place a simple definition from [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/] instead:
A closure is a function/method that has the following two properties:
* You can pass it around like an object (to be called later)
* It remembers the values of all the variables that were in scope when the function was created.
It is then able to access those variables when it is called even though they may no longer be in scope.
How cool is that?! Check how human-friendly and explanatory it is comparing to the current one:
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.
Any thoughts on that?
Thanks! [[User:Alex Ex|Alex Ex]] ([[User talk:Alex Ex|talk]]) 15:52, 1 April 2011 (UTC)
:+1 --[[User:Paddy3118|Paddy]] ([[User talk:Paddy3118|talk]]) 17:04, 1 April 2011 (UTC)
: The first sentence could be improved, but I don't think your suggestion is an improvement. You sort of try to define "first-class function" and "closing over the lexical scope", but do so in a incorrect and non-universal way. E.g. "pass around like object" probably only makes sense to people coming from an OO background. A closure doesn't "remember the values", it gives you access to the variables itself (I initially made the same mistake [http://en.wikipedia.org/w/index.php?title=First-class_function&action=historysubmit&diff=413714790&oldid=413713398 here]). You also need to be explicit about which scope you're talking, in this case the lexical scope, not the dynamic scope. This again might be "obvious" for people coming from a particular language, but isn't universal. Your definition simply leaves out the second sentence from the current definition altogether. I think a concrete example, as in [[First-class function#Closures]] would be more instructive. —''[[User:Ruud Koot|Ruud]]'' 12:43, 2 April 2011 (UTC)
: Also, closures can close over more than just the variables in the lexical scope, but other lexical entities entities (e.g. <code>this</code>, target of <code>return></code> and <code>break</code>, ...) as well. The current lead doens't mention this yet. —''[[User:Ruud Koot|Ruud]]'' 12:52, 2 April 2011 (UTC)
: To see a closure does not just "remember values" try:
<syntaxhighlight lang="python">
Python 3.1.2 (release31-maint, Sep 17 2010, 20:27:33)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... x = 0
... def g():
... nonlocal x
... x = x + 1
... return x
... def h():
... nonlocal x
... x = x + 1
... return x
... return [g, h]
...
>>> [a,b] = f()
>>> [c,d] = f()
>>> a()
1
>>> a()
2
>>> b()
3
>>> a()
4
>>> c()
1
>>> d()
2
</syntaxhighlight>
: —''[[User:Ruud Koot|Ruud]]'' 13:11, 2 April 2011 (UTC)
: Also, Finkel gives a pretty similar definition to the current one: "A procedure in combination with its nonlocal referencing environment is called a '''closure'''." And then continues with "Because this idea is unfamiliar to students who mainly use C (which has no nested procedures, and therefore no nonlocal referencing environments), I will present several examples." I think we should use the same approach. —''[[User:Ruud Koot|Ruud]]'' 19:31, 2 April 2011 (UTC)
:: Okay. We agree the current text ''needs'' improving, yes? --[[User:Paddy3118|Paddy]] ([[User talk:Paddy3118|talk]]) 04:54, 3 April 2011 (UTC)
::: Sure, it definitely suffers from a bad case of too-many-editors(-who-didn't-all-quite-grasp-the-subject), but I don't think Alex's proposal is the way to go. —''[[User:Ruud Koot|Ruud]]'' 10:35, 3 April 2011 (UTC)
Agree, it's bad. One problem not addressed here is; '''the target audience is only experienced computer scientists.''' Doesn't that violate the Wiki policy of addressing non-experts first? ( "Provide an '''accessible''' overview" )...particularly in the lead section? ...with the resulting pitfall of making true statements rather than explanations or definitions. (Sometimes almost as if people were creating test questions or facts lists, or being worried about violating little nit-picky "experts," loudly-proudly waving tightly clutched brand new syntax guides.)
For example, first sentence; <BR>
"''a closure ...is a function together with a referencing environment for the nonlocal names (free variables) of that function.''" is technically true, but it's utterly dependent on jargon and highly specialized training to have any meaning....as if a definition for already-experts...to satisfy experts...huh?
All that a typical person wants from the intro is
to loosely grasp the concept of closure. Only after that required goal is met is any other goal useful or desired. The intro should concentrate on teaching, not technical correctness. There should be an opening sentence like, "The purpose/advantage of closure is..." so people have an orderly place to hang and orient the abstract definitions, --to help solidify them.
It's important to remember that many/most people come here as the result of following a hyperlink with the goal only of understanding another article. They will never read beyond the first sentence, paragraph or the lead section. In that context, ''hit-wise'', the intro is the most valuable part of the article. See: [[Wikipedia:Manual of Style (lead section)]] <BR> --[[Special:Contributions/69.227.84.108|69.227.84.108]] ([[User talk:69.227.84.108|talk]]) 19:42, 28 May 2011 (UTC)Doug Bashford
== Clarify Part of Speech ==
I came to this article because I have read statements like, "Language X has Closures," and "The Closure of function f is...," and "By line x, closure has occurred." Is Closure a noun or a verb? This article didn't clear it up at all, obviously, both, but then the first line of the abstract, treating it as a noun, keeps other parts of the abstract unclear. Someone knowledgeable should clarify this, and all editors should keep this in mind. (This is in no way a problem limited to this article alone.) --[[User:Limited Atonement|Limited Atonement]] ([[User talk:Limited Atonement|talk]]) 18:07, 30 August 2011 (UTC)
: The ''act of'' "closing a function over its free variables" results in an object called "''a'' closure". It's usually a noun, but can be used as a verb. I don't think this is a very uncommon phenomena? —''[[User:Ruud Koot|Ruud]]'' 18:55, 30 August 2011 (UTC)
== Clarity ==
How the first paragraph reads to someone with little formal training in programming:
''In computer science, a closure (also lexical closure, function closure or function value) is a function together with a NOUN for the NOUN (NOUN) of that function. Such a function is said to be "ADJECTIVE PHRASE" its NOUNS. The NOUN VERBS the NOUNS to the NOUNS in scope at the time the closure is created, additionally extending their lifetime to at least as long as the lifetime of the closure itself.''
I don't really know what a closure is from this article. I read something on stack overflow ([http://stackoverflow.com/questions/111102/how-do-javascript-closures-work explain JavaScript Closures to a 6 year old]), and I think something like this might be more clear (if someone could make it more accurate, since like I said, I don't really understand yet):
''In computer science, a closure is a function which returns another function. Importantly, the returned function has access to the variables contained in the returning function's scope.
'' <span style="font-size: smaller;" class="autosigned">— Preceding [[Wikipedia:Signatures|unsigned]] comment added by [[Special:Contributions/204.87.16.4|204.87.16.4]] ([[User talk:204.87.16.4|talk]]) 18:50, 20 September 2011 (UTC)</span><!-- Template:Unsigned IP --> <!--Autosigned by SineBot-->
: I've been think about this for a while, but I'm sure if it possible to explain what a closure is in a single sentence. Do the examples at [[First-class function#Non-local variables and closures]] help you to understand what the purpose of a closure is? If so, they should probably be copied to somewhere near the beginning of this article as well. If not, could you try explain what is still difficult to understand for you?
: 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)
:::: Very helpful, thank you! I think I see the dilemma now, between clarity and precision. My only recommendation is to avoid giving the reader another definition in the second sentence. Follow with very simple language to catch anyone who was left behind.
::::''In computer science, a closure (also lexical closure, function closure or function value) is a function together with a referencing environment for the non-local variables of that function. In other words, a closure allows a function to access some variables outside its typical scope.'' --[[Special:Contributions/204.87.16.4|204.87.16.4]] ([[User talk:204.87.16.4|talk]]) 13:00, 22 September 2011 (UTC)
::::: Good suggestion. I think the "typical" part might still need to be changed. We are talking about variables that are still in the lexical scope, but might by outside of the dynamic scope. Most (non-LISP) programmers would probably assume "typical" refers to lexical scope here. —''[[User:Ruud Koot|Ruud]]'' 13:55, 22 September 2011 (UTC)
:"''In computer science, a closure (also lexical closure, function closure, function value or functional value) is a function together with a referencing environment for the non-local variables of that function.''" This sentence is by far the most confusing thing I've ever seen. I'm almost on the floor laughing from how vaguely confusing it is. Firstly the usage of "together with" in this sentence is nothing more than weasel words here and add insult to injury in this confusing context. I see what you guys are trying to do here by trying to define a closure in one sentence but we shouldn't be tossing around confusing words like that before the end-user at least knows what we are talking about. If anything, I think it would be best if we flipped some things around in this sentence. Can we re-word the sentence to something more like this?: ''In computer science, a closure (also lexical closure, function closure, function value or functional value) is the scope of a function that that has a referencing environment for variables which are not local to it that appear in a parent, and in most cases not global, scope.'' --[[User:Thelazyleo|<span style="color:blue;">T<span style="color:royalblue">he</span>l<span style="color:royalblue">azy</span>l<span style="color:royalblue">eo</span></span>]] ([[User talk:Thelazyleo|<span>talk</span>]]) 20:39, 28 December 2011 (UTC)
:: In my opinion your suggestion is more confusing and less accurate than the current wording. Operationally, a closure is a data structure pairing a function (reference/pointer) with a table (the referencing environment). See for example the definition by Sussman and Steele given in the first footnote. This is a fairly unambiguous and precise definition (given that you know what a referencing environment is, what necessarily has the be explained in the following sentences.) Your proposed definition on the other hand uses the rather vague and imprecise "a closure ... is the scope of a function". Semantically, a closure has everything to do with scoping, of course, but this is what the sentences following the first try to explain. I therefore think it's only useful to whole first paragraph, not just the first sentence. —''[[User:Ruud Koot|Ruud]]'' 21:45, 28 December 2011 (UTC)
:: I do think that the final part of the first sentence ("for the non-local variables of that function.") needs to be clarified. In particular it might be possible to give a definition of "referencing environment" instead. Something along the lines of "a map containing [[name binding|binding]]s for the [[non-local variable]]s of that function."?—''[[User:Ruud Koot|Ruud]]'' 21:47, 28 December 2011 (UTC)
::I have taken the liberty to remove the terms ''function value'' and ''functional value'' from the first sentence. These terms do not usually refer to closures, except of course in the context of languages in which all function values are closures, but there are many languages in which this is not the case. [[User:Rp|Rp]] ([[User talk:Rp|talk]]) 12:38, 31 March 2012 (UTC)
== First Example (Python) ==
Please note that I have never written a line of code in python and have no idea how variables are initialized and values assigned.
But I am worried that the following snippet that is used as the first example in the article may have an error. Can someone please help me understand where the value for 'y' is initialized in the incrementer() function? I understand that the lambda function would have access to 'x', which is defined within it's parent function. But, in the first call to (initialization of) incrementer, the value of y=undefined, but the snippet seems to indicate that it is initialized to 0(int).
def incrementer(x=1):
return lambda y: x+y
incr1 = incrementer(1)
print incr1(2) # 3
incr2 = incrementer(2)
print incr2(3) # 5
[[Special:Contributions/166.248.77.56|166.248.77.56]] ([[User talk:166.248.77.56|talk]]) 03:26, 11 February 2012 (UTC)
:<code>lambda arguments: expression</code> is an unnamed function that behaves as if defined like this:
<pre>def name(arguments):
return expression</pre>
:So <code>incrementer(1)</code> is itself a function which adds 1 to its argument (named <code>y</code>). [[User:Johnuniq|Johnuniq]] ([[User talk:Johnuniq|talk]]) 06:12, 11 February 2012 (UTC)
: The example was recently replaced. My [http://en.wikipedia.org/w/index.php?title=Closure_%28computer_science%29&oldid=473219244#Example old example] was IMHO clearer. The other editor apparently found it [http://en.wikipedia.org/w/index.php?title=Closure_%28computer_science%29&action=historysubmit&diff=475069300&oldid=473219244 too verbose], but this was intentional as it has to be understandable to non-Python programmers too. —''[[User:Ruud Koot|Ruud]]'' 11:14, 11 February 2012 (UTC)
: Also, the new example fails to demonstrate that the state captured in a closure can be mutable. I'll restore the old example. —''[[User:Ruud Koot|Ruud]]'' 11:19, 11 February 2012 (UTC)
::I agree that the lambda code is too mysterious to be helpful here, and the example you just restored is better. [[User:Johnuniq|Johnuniq]] ([[User talk:Johnuniq|talk]]) 01:59, 12 February 2012 (UTC)
: I find the [https://en.wikipedia.org/w/index.php?title=Closure_(computer_programming)&oldid=595411369#Example | current example] misleading since the closure returned by <code>counter</code> is an impure function, printing different values for calls on the same argument. The fact that the state captured in a closure can be mutable is important, and should be mentioned somewhere in the article, but presenting this as a canonical example is likely to mislead readers into thinking that closures are by nature impure (misleading since purely functional languages like Haskell of course allow closures as well). —[[User:Smerdis|Smerdis]] 27 February 2014 <span style="font-size: smaller;" class="autosigned"> — Preceding [[Wikipedia:Signatures|undated]] comment added 20:26, 27 February 2014 (UTC)</span><!--Template:Undated--> <!--Autosigned by SineBot-->
: This article has several significant problems.
For one thing it frequently bases its assertions about whether some language x, has closures with how they are implemented in said language. For example, when one says that D and C# use delegates in this context, one suggests that delegates are somehow fundamentally related to the semantics of closures. Delegates are a technique to implement function references in object a fashion which implicitly captures the object to which the method belongs, allowing it to be invoked in a type safe and polymorphic manner on the correct instance/static. C# captures represents references to functions via delegates, but that is not why it has closures. It has closures because its function values are lexically scoped such that, when invoked, they execute in the lexical context in which they were defined. The fact that they can be, and usually are, stored in delegate instances is merely a low level detail.
Additionally the question of purity vs impurity of functions is a broader topic.
[[User:Rahab rx|Aluan Haddad]] ([[User talk:Rahab rx|talk]]) 08:47, 20 March 2014 (UTC)Rahab_Rx
== First example needs one more information ==
I think that the first example with ''function startAt(x)'' should explain from where the variable ''y'' comes and how it gets its value changed. This is implicitly told below the example by giving the result for <code>closure<sub>1</sub></code> & <code>closure<sub>2</sub></code>, but a verbal explanation is missing.--[[User:Sae1962|Sae1962]] ([[User talk:Sae1962|talk]]) 12:12, 5 February 2015 (UTC)
== Functions in C -- Clarity recommended... ==
''Closures typically appear in languages in which functions are first-class values—in other words, such languages enable functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers.''
Earlier, it is indicated that 'c' is not such a language, and does not allow nested functions, but, in essence, via pointers, it does. You cannot expressly pass a function, but you can pass a pointer to a function, and this allows you to do some stuff that looks remarkably indistinguishable from those used in the examples of legitimate usage of closures.
I'm not arguing agains the claim, but suggesting that it would be good to discuss this somewhere as to how it differs.[[Special:Contributions/167.230.96.8|167.230.96.8]] ([[User talk:167.230.96.8|talk]]) 20:04, 13 May 2015 (UTC)
: There is some discussion about this at [[First-class function#Non-local variables and closures]]. —''[[User:Ruud Koot|Ruud]]'' 13:28, 14 May 2015 (UTC)
I'm confused about the claim that C doesn't support nested functions; recursion is a standard technique in C, so it clearly does support nested functions. It doesn't directly support passing a function as a value, so they aren't first-class values. It doesn't support closures, due to not being able to execute the function after the enclosing function has exited, but that is the other case. This wording seems almost like a typo, but I'm not fluent enough in Algol to make that edit. Perhaps the source of my confusion is that C doesn't allow nested function definitions. If so, perhaps clarifying that would help other readers with a similar confusion.--[[User:Wcoole|Wcoole]] ([[User talk:Wcoole|talk]]) 23:08, 21 October 2015 (UTC)
:: ''Nested functions'', in this contaxt, means ''lexically'' nested functions. Last time I used C, gcc supported them while standard C didn't. (The next question is then whether such functions can be closures, i.e. use variables defined in their lexical environment when invoked outside of that scope.) [[User:Rp|Rp]] ([[User talk:Rp|talk]]) 12:27, 20 March 2018 (UTC)
== Capture-by-value in the lead section ==
{{ping|Maggyero}} I'm not sure if I completely agree with [https://en.wikipedia.org/w/index.php?title=Closure_%28computer_programming%29&type=revision&diff=729749204&oldid=723316111 these] changes to the lead section. These changes allow for the possibility of a closure capturing variables by value instead of by reference. If feel this distinction is overly pedantic for the lead section, and makes it even harder to understand. Especially considering that the distinction only makes sense at all in imperative languages/language where variables are mutable, and even more so since C++ is the only language I'm aware of that allows capturing by value. Instead I'd suggest assuming immutable variables/capture-by-reference semantics in the lead and go into more detail on capture-by-value in a footnote and/or separate section on closures in imperative languages. —''[[User:Ruud Koot|Ruud]]'' 15:08, 14 July 2016 (UTC)
== Small typos or not? ==
Hi, these two seemed to me as typos but I'm not sure, and this is my first attempt to contribute to wp.. In '''Delegates (C#, D)''' section, the sentence "For example, the above code will not work correctly, because the variable a is on the stack, and after returning from test(),..." it is not clear to which function test() refers, test1(), test2() or both? And in the last sentence "The same is true for inner's class methods that..." should it be "inner" instead of "inner's class methods" or am I missing something? --[[User:S.POROY|S.POROY]] ([[User talk:S.POROY|talk]]) 19:45, 15 May 2017 (UTC)
== Example and text don't match ==
I was reading this article and found this mismatch in section "Lexical environment". There is no <code>foo</code> function nor <code>f</code> or <code>g</code> variables. I think the text is referring to the example in section "Anonymous functions". Example and text follows:
<syntaxhighlight lang="ecmascript">
'use strict'
function makeFunc() {
const name = "Closure";
function displayName() {
console.log(name);
}
return displayName;
};
const runFunc = makeFunc();
runFunc(); //Closure
</syntaxhighlight>
Note how function<code>foo</code> and the closures referred to by variables <code>f</code> and <code>g</code> all use the same relative memory ___location signified by local variable <code>x</code>.
[[User:Bjacquet|Bjacquet]] ([[User talk:Bjacquet|talk]]) 11:59, 19 March 2018 (UTC)
|