Talk:Closure (computer science)

In perl at least, a closure doesn't have to be a function definition. It's more or less anything between a pair of braces, that serves as it's own variable scope. In Damian Conway's Object Oriented Perl, I believe he uses closures to implement the private variables of an object, so it might be misleading to say that the closure itself is an object or acts like one. In any case, something needs to be said about scope here. Wesley

How could one use a closure that's not a function definition?

Regarding the "acts as an object" comment, I was thinking of a closure like this:

sub counter {
    my $x = shift;
    return sub { print "$x\n"; $x--; };
}

$h = counter(4);
$g = counter(7);

&$h();  # gives 4
&$h();  # gives 3
&$g();  # gives 7
&$h();  # gives 2
AxelBoldt

A closure can be used as a way to simulate static variables. For instance consider the following (slow) function:

sub fib {
  my $n = shift;
  if ($n <= 1) {
    return 1;
  }
  else {
    return fib($n-1) + fib($n-2);
  }
}

It works, but calculating (say) fib(40) may take a while. Now let's add a private closure in which we cache results (this kind of caching is known as memoizing):

{
  my %cache;
  sub fib {
    my $n = shift;
    if ($n <= 1) {
      return 1;
    }
    elsif (exists $cache{$n}) {
      return $cache{$n};
    }
    else {
      return $cache{$n} = fib($n-1) + fib($n-2);
    }
  }
}

Now the function runs much more quickly. If we had static variables (the "my $foo if 0;" bug does not count in my books!), that would be the right way to do this, but closures can do it as well.

BTW I hope that the example I gave is not too complex. I wanted to provide something that was accessible but gave an idea of why someone might choose to use closures.

bjt


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.

If you want to do a more involved programming example, IMO you should create an article for first-class function or higher-order function and write it there; or, better still add it to functional programming. The term "closure", as commonly used by language designers/implementors, refers specifically to the data structure with the code pointer and environment pointer. Programming using higher-order functions is a broader idea, and belongs in a broader article. k.lee 00:44, 24 Oct 2003 (UTC)


Re: typical implementation as "a set of values that record the values of the relevant variables in the function's lexical environment at the time of binding", this was not correct. A naive Lisp interpreter can implement a closure as a pair containing a pointer to the function and a pointer to the actual lexical environment (activation record) at the point of capture. There's no recording of values, or selection of relevant variables for capture. Wasteful and slow, but adequate. k.lee 17:27, 24 Oct 2003 (UTC)


I have just edited the page such that the Java simulation section has "final" instead of "immutable". My understanding of the term immutable in the context of Java is that it means once you have a reference to the object its internal state will never change i.e. all fields (including private ones) can be declared final and all references that the object holds are themselves to immutable objects. This property, as far as I know, is not detected or enforced by the runtime and is not necessary for a local variable to be used in an anonymous inner class. The meaning of the keyword final, on the other hand, is that the value of the variable will never change which object it references (or will never change value if a primitive). It is this that is necessary for the anonymous inner type to make use of the variable so that the runtime can simply clone the primitive values and object references of final variables on the stack when instantiating the anonymous inner class.

--Jwal 18:35, 12 Jun 2004 (UTC)



Why Python doesn't have closures:

Python has nested scope, but not the ability to modify variables in outer lexical scopes (except for globals, and via reflexion). Therefore, Python doesn't have closures. It's that simple. --Lament

Removed "merge this with Function object" note

Closures are a critically important concept in programming languages (and computer science) and definitely deserve their own separate article. They are different from Function objects, despite the fact that the two are sometimes confused.

First, it does not concern us if a topic is imporant or not. If there is no article named closure, it would never mean that closure is an unimportant topic as long as the topic is well covered. Second, it is not clear to me the difference between the two, and since the "current" content of this article is similar to that in function object, I suggest we merge the two. -- Taku 07:45, Jun 8, 2005 (UTC)
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. Wouter Lievens 09:05, 8 Jun 2005 (UTC)
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. -- Taku 09:18, Jun 8, 2005 (UTC)
If the example is bad, then it needs to be rewritten. It doesn't mean the article has to be merged with an unrelated random other article. You might as well merge it with Lambda Calculus. Also, the example isn't a bad one, and it doesn't even closely resemble a function object, as it is expressed in ML, which isn't object-oriented. If in your view closures and function objects are the same thing, you need to get your concepts straight. Wouter Lievens 10:15, 8 Jun 2005 (UTC)
My concepts of function objects and closure are those put in each article.
a closure is an abstraction representing a function, plus the lexical environment (see static scoping) in which the function was created, and its application to arguments.
A function object, often called a functor, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax.

The definition of a closure awafully resembles that of a function object in Java, for instance. Take this:

interface Function {
  public int map (int y);
}
final int step = 2;
new Function () {
  public int map (int y) { return y + step; }
}

I am not suggesting the example in the article is bad. It shows what is a closure. And I am still waiting to see what is a difference. I can't find this anywhere yet. Finally, a function object is certainly not limited to object-oriented languages. I think it's an old concept originated in functional programming. Maybe I am missing something. -- Taku 11:41, Jun 8, 2005 (UTC)

A function object is something you create in object-oriented programs to make up for the lack of proper first-class and higher-order functions (i.e. closures). OOP languages that support closures (e.g. Smalltalk) typically do not use function objects (as shown in the example), because the presence of closures removes the need for function objects. However, as closures in such languages (e.g. Smalltalk blocks) are modelled as objects, they do resemble function objects. But the typical languages where function objects are used (such as C++ and Java) do not support lexical environment closure, and thus function objects are not equivalent and not even related. The key feature of a closure is the environment link. A function object in C++ can be best compared to a function pointer in C, in that it can be invoked and passed around dynamically. Closures are not supported in C++ because the language's activation record model is entirely stack-based. Java anonymous inner classes fix this halfway by providing syntactic sugar for using final variables in the closure, but these are in fact translated to parameters to the anonymous class. So to summarize: a function object is an object that behaves semantically (and sometimes syntactically) like a function, whereas a closure is a function extended with its environment of definition. Some function objects may be in fact closures, and some closures may in fact be objects (Smalltalk blocks), which means the two concepts may overlap. But they definately don't have to. Wouter Lievens 12:43, 8 Jun 2005 (UTC)
Good now I see your distinction. But I don't think this is large enough to warrant two separate articles. Obviously not everyone sees this distinction, for one. It is true that some closures that are never function objects, and some function objects have no relation with closure. But it does not mean they cannot be discussed in one article. Certainly, the usage of a function object is similar to that of closure. And I still think, like the above post, discussing the two concepts is helpful for readers. Take negative and non-negative numbers. A negative number is never positive, but discussing two numbers in one place helps readers understand the two concepts. If you think a term function object would cause confusion, we can simply rename it. -- Taku 23:15, Jun 8, 2005 (UTC)
I think each distinct subject deserves its own page. What can possibly be gained from merging these (rather unrelated) pages together? More precisely, it would introduce serious problems in terms of categorization. For instance, function object would belong in [[Category: Object-Oriented Programming]], whereas closure (computer science) definately does not. In analogy, we might as well put President and King in the same page, as they're related too (both are heads of state). Wouter Lievens 09:56, 22 Jun 2005 (UTC)
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. Wouter Lievens 10:01, 22 Jun 2005 (UTC)
Navigation

  • Art and Cultures
    • Art (https://academickids.com/encyclopedia/index.php/Art)
    • Architecture (https://academickids.com/encyclopedia/index.php/Architecture)
    • Cultures (https://www.academickids.com/encyclopedia/index.php/Cultures)
    • Music (https://www.academickids.com/encyclopedia/index.php/Music)
    • Musical Instruments (http://academickids.com/encyclopedia/index.php/List_of_musical_instruments)
  • Biographies (http://www.academickids.com/encyclopedia/index.php/Biographies)
  • Clipart (http://www.academickids.com/encyclopedia/index.php/Clipart)
  • Geography (http://www.academickids.com/encyclopedia/index.php/Geography)
    • Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
    • Maps (http://www.academickids.com/encyclopedia/index.php/Maps)
    • Flags (http://www.academickids.com/encyclopedia/index.php/Flags)
    • Continents (http://www.academickids.com/encyclopedia/index.php/Continents)
  • History (http://www.academickids.com/encyclopedia/index.php/History)
    • Ancient Civilizations (http://www.academickids.com/encyclopedia/index.php/Ancient_Civilizations)
    • Industrial Revolution (http://www.academickids.com/encyclopedia/index.php/Industrial_Revolution)
    • Middle Ages (http://www.academickids.com/encyclopedia/index.php/Middle_Ages)
    • Prehistory (http://www.academickids.com/encyclopedia/index.php/Prehistory)
    • Renaissance (http://www.academickids.com/encyclopedia/index.php/Renaissance)
    • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
    • United States (http://www.academickids.com/encyclopedia/index.php/United_States)
    • Wars (http://www.academickids.com/encyclopedia/index.php/Wars)
    • World History (http://www.academickids.com/encyclopedia/index.php/History_of_the_world)
  • Human Body (http://www.academickids.com/encyclopedia/index.php/Human_Body)
  • Mathematics (http://www.academickids.com/encyclopedia/index.php/Mathematics)
  • Reference (http://www.academickids.com/encyclopedia/index.php/Reference)
  • Science (http://www.academickids.com/encyclopedia/index.php/Science)
    • Animals (http://www.academickids.com/encyclopedia/index.php/Animals)
    • Aviation (http://www.academickids.com/encyclopedia/index.php/Aviation)
    • Dinosaurs (http://www.academickids.com/encyclopedia/index.php/Dinosaurs)
    • Earth (http://www.academickids.com/encyclopedia/index.php/Earth)
    • Inventions (http://www.academickids.com/encyclopedia/index.php/Inventions)
    • Physical Science (http://www.academickids.com/encyclopedia/index.php/Physical_Science)
    • Plants (http://www.academickids.com/encyclopedia/index.php/Plants)
    • Scientists (http://www.academickids.com/encyclopedia/index.php/Scientists)
  • Social Studies (http://www.academickids.com/encyclopedia/index.php/Social_Studies)
    • Anthropology (http://www.academickids.com/encyclopedia/index.php/Anthropology)
    • Economics (http://www.academickids.com/encyclopedia/index.php/Economics)
    • Government (http://www.academickids.com/encyclopedia/index.php/Government)
    • Religion (http://www.academickids.com/encyclopedia/index.php/Religion)
    • Holidays (http://www.academickids.com/encyclopedia/index.php/Holidays)
  • Space and Astronomy
    • Solar System (http://www.academickids.com/encyclopedia/index.php/Solar_System)
    • Planets (http://www.academickids.com/encyclopedia/index.php/Planets)
  • Sports (http://www.academickids.com/encyclopedia/index.php/Sports)
  • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
  • Weather (http://www.academickids.com/encyclopedia/index.php/Weather)
  • US States (http://www.academickids.com/encyclopedia/index.php/US_States)

Information

  • Home Page (http://academickids.com/encyclopedia/index.php)
  • Contact Us (http://www.academickids.com/encyclopedia/index.php/Contactus)

  • Clip Art (http://classroomclipart.com)
Toolbox
Personal tools