In perl, a closure is implemented as an anonymous subroutine. You can think of it as something of a function generator.

sub greet {
  my $salutation = shift();
  return sub { print "$salutation " . shift (). "\n"; };

my $a = greet( "Hello" );
my $b = greet( "Bonjour" );

So now if you call &$a("World"), "Hello World" will print. If you call &$b("La Monde"), "Bonjour La Monde" will print. Closures are useful if you want to bind a particular value of a lexical variable to a function.

In general, a closure is a function taken together with an environment. Closures are applicable in languages which: A closure has the lexical environment of the point where it was created, no matter where it is called from.

The important bit in eric+'s program above is the `my' on the second line, which makes $whom a lexically-scoped variable. If it were changed to `local' (which introduces a new binding of a dynamically-scoped variable), the calls `&$a("World")' and `&$b("La Monde")' would produce warnings because no variable named `$salutation' would be in scope when they were called.

Closures are common in functional languages; Perl is such a mongrel that it could be considered a functional language. An example (in Scheme) paralleling eric+'s example above is:

(define (greet salutation)
  (lambda (whom) (display (string-append salutation " " whom "\n"))))

(define a (greet "Hello"))
(define b (greet "Bonjour"))

(a "World")      ; prints "Hello World\n"
(b "la Monde")   ; prints "Bonjour la Monde\n"
Closures are often implemented as thunks which know the address of the function, as well as that of its activation record. Also common are `fat pointers', which are wide enough to contain the addresses of both the function and its activation record.

psychobabble commonly used to also describe the achievement of getting over it when you split up from a relationship. You have closure at the point where you no longer jump at your answering machine at 4am when you come home drunk with your heart leaping at the prospect that your ex has left a message along the lines of "I got it all wrong, I NEED you back and I can't live without you". Just to discover it was only your mother reminding you of your Great Aunts birthday party Sunday

Closure is not when your ex turns up at your apartment to collect some of their things they forgot to pick up before and you end up in bed together, waking up the next morning with the two of you in a state of serious emotional hangover

(General Topology:)
The closure of a set A in a topological space T is the "smallest" closed set containing A. Note that intersections of closed sets are themselves closed, so this is precisely the intersection of all closed sets containing A.

Contrast (topological) interior.

There's the box of memories I have which is basically a bunch of holiday snapshots. Stuff I did with friends. I look through them now and again, when I run out of images. Halfway up a mountain in a tent which is being washed away by heavy rain and held up by giggling shouting people in wet pyjamas, that kind of thing. Most of them have audio, mainly laughter tracks, background music. Some are spectacular. Some are just funny.

Then there's the box I guess a lot of people have. The one with old letters. The one you keep at the bottom of a closet or in a drawer nobody uses. Under the bed is too obvious. I put them there and I almost never look at them unless I come across the box while in search of something else. When this happens, I am surprised at how little they move me.

Sometimes I wonder why I keep all this old junk around. Is it necessary to have a record that you felt certain emotions, or did certain things? Does it just fill up space that could be used to store new material? Or is it a concrete lid covering the well of the vast black pit of nothingness that you might fall into, without it?

A sample. Sometimes strangers bring surprises, and unlooked-for gifts. Gallant, he was. There went my preconceptions. Dark handsome American Jewish intellectual, I thought he was bound to be full of arse. We were talking about Baudrillard because I noticed the title of his book, and his face suddenly lit up and he said in mid-sentence: "Would you like a copy?" Startled, I nodded, and he got up, clambered over the table crushing us in, leapt off and disappeared in the direction of the bookshop. I looked at Jo, frowning puzzled: she grinned and said: "I think he likes you."

Nobody had stolen me a book in so long. I carried it about for days, revelling in its clean shiny edges. Someone new to talk to. Then he went and spoilt it by inviting me out to dinner, a blatant request for more. I declined, not being vacant or interested. He pointedly sat on the other side of the coffee bar after that and ignored me. Angry with him for even asking, I ignored him back. All I wanted was someone to swap amusing banter with, catch the odd movie with. Casual, relaxed, pleasant. The kind of thing that keeps the days rattling along comfortably. He seemed to want mess and confusion and intensity. Yet I read an essay of his once: it was a surprisingly calm and orderly piece of work. Dry, even. Very unlike mine which back then were full of Sturm und Drang, passionate support or scathing denial. Pen picked steaming off the page, words charred into the whiteness. I often saw my head back then as a tindery dry place, the Australian Outback, maybe. Flames easily sparked and spreading like wildfire.

I was not vacant, but I was not exactly engaged. Busy, obsessed, working all night sometimes, love switched to low maintenance. I felt at the time that I didn't understand sex. A short messy physical procedure, what's the big deal? Three years into a relationship, there was nothing to make me want to be bothered. Tiring. All that getting undressed and dressing up again. Having to work yourself up into it, wanting nothing better than to be left alone, to let out the irritated sigh which is pushing at the inside of your face, causing you to be wearing The Wrong Expression. Batter it down. Put on a smile, close your eyes, accept the role and play it. Wondering how much of his response is acting too. Wondering what happened to desire.

I began to start fights about nothing, or about something in the past. Obvious now, when I look at it, what I was up to. Trying to trigger the intensity that leads to desire, desire being the element that connects the short messy physical procedure with something else. Thinking that if you could not read, it would still be possible to sit quietly looking at every page in a book, if you were required to. Idly noting: that black squiggle looks like a caterpillar, that one like a snake, this one like a bus queue full of people. But basically bored. Wanting it over, sneaking glances at the clock. Wondering what the point is.

Tears on both sides and then violence. The passionate making-ups that I had unconsciously envisaged never happened: wrong kind of intensity. Too tired, too drained by the floods of fucked-up emotion weathering us, eroding our skin to red rawness. Friends noticing the black eye that was probably all my fault anyway, and saying nothing, but dragging me out to go clubbing. In clubs I would find myself searching the room for him. All the people somehow made the room seem emptier. Looking through the spaces between bodies, fidgeting in my seat, scanning, scanning for anything that might break the mould of boredom and disinterest. It's dried up and dead, he said. We should finish it. I thought so too, so why did I feel like screaming and begging to keep it?

Separated. Ghost limb still present despite the public appearance of a neatly healed stump. Friends rallying round, slaps on the back, the chink of glasses. Saying what they think you want to hear. "Yer well rid I reckon luv. Game of pool, eh?" Keeps you going while you're stumbling around, stumpy. Like an artificial leg: fills the gap but doesn't do much for the neurological damage. Inside, attempting to find answers. Does desire always have to end, jesus god if something this perfect could go wrong then there's no hope for anything, blah de blah de blah in endless circles. Boring yourself sick.

Bad things happen, we wonder why. Faced with them I find myself flipping through selections of approaches, looking for an action sequence. The Zen approach: these things happen and it's nobody's fault and you just have to calmly wait them through, get on with it, move on. The taking-all-the-responsibility approach: it's all my fault, if only I hadn't done x or y or z, I Must Change I Am So Crap. The blame approach: if only he had done x or y or z to make me want him. The chicken-and-egg approach: did all the x start the y? The irritable approach: aw hell it's all a load of bollocks now, forget it. But you never quite do, not until much later. These sequences replay endlessly but choppily, never finding the groove, the seamless perfectly mixed edit to unite the thread in magical flow. That would explain everything, provide closure, end the project.

Then years later you open that box, and there's nothing in it but dry paper, crumpled drawings, old photos. You look with idle curiosity but no pain: perhaps a little nostalgia, for who you used to be, maybe. And realise that closure has just quietly taken place, when you were not looking: that this is how it works.

The Power of Closures

neil's definition of a closure is accurate, but what's missing is the why? Programmers in languages that emphasize closures swear by them. A lot of programmers don't even know what they are, and maybe a larger number understand closures, but don't really understand their utility. Let me propose an expanded definition:

A closure is a function and its environment that can be passed into another function

The important part here is the environment which consists of all variables defined at the scope of the closure creation. The essential functionality is both a form of encapsulation and abstraction. Observe this Ruby example:

def find_birthdays_in_range(min,max)
  birthdays = [ "1970-06-15", "1975-08-13", "1939-03-21", "2001-12-01" ]
  birthdays.find_all { |birthday| birthday > min && birthday < max }

So essentially there are 3 functions here that are called from within each other. The third and final one is the closure defined by the ruby block in curly braces, it accepts one parameter called birthday. For easy reference, refer to these function as follows:

A : find_birthdays_in_range
B : find_all
C : anonymous block

Now normally in a lexically-scoped language (almost all of them nowadays) a function can only access parameters passed into it directly. But in this case function C has access to variables defined in function A. That's where the encapsulation comes in, function B never knows anything about min and max. Without closures then function B would have to receive those variables as parameters, and in turn pass them to the anonymous block. But then the generality of function B would be destroyed—it would accept exactly 2 parameters and pass them through to function C. The problem is that those 2 parameters don't really mean anything to find_all. find_all is meant to be able to match members of an array by arbitrary criteria. Function C could just as well reference no variables or 20 variables in determining whether an element of birthdays matches its criteria, and then what?

Without closures it's not really sane to use this structure. Most likely in Java or PHP you would just make find_birthdays_in_range do everything itself. Instead of calling find_all on the array, it would loop through the array itself and gather the matching birthdays manually. There's really nothing wrong with that approach, but you end up writing a lot of the same looping and collecting code over and over. That's where the abstraction comes in. Closures give you the opportunity to write much more general functions.

find_all can find members of an array that match literally any criteria you can express in code, and that's just a relatively basic function that uses closures. You can write any function to call a closure from within, thus generalizing the function. Some examples from the ruby standard library:

  • find lets you specialize what constitutes a match.
  • sort lets you specialize how one object is determined to be greater or less than another object.
  • collect lets you apply an arbitrary transformation to all the members of a collection.
  • gsub lets you make substitutions more complex than a simple regex substitution allows.

In short, closures expand the power of abstraction available to functions.

"Closure" is a song by the band Chevelle, released on the album Wonder What's Next in 2002. It is notable in that it really should come with a warning sticker. I'm not normally in favor of stickers; I'm with Tesla on that. But this one is special.

The sticker should say something like, "Warning: Do not under any circumstances listen to this song while depressed. Bodily harm could result."

And then at the end of the song it should warn you again, just in case it made you depressed, to not under any circumstances listen to "Am I Alone In Here" next, or within six months of any relevant tragedy or psychological event or diagnosis.

"Closure" is moving, like an ecstatic Opus Dei member drawing blood is moving; but "Am I Alone In Here" is such an amazing piece of artistry that people have been known to listen to the end and then wonder where they got that gun and how long it's been between their lips.

Perhaps really good art sometimes does need a warning.

Clo"sure (?, 135), n. [Of. closure, L. clausura, fr. clauedere to shut. See Close, v. t.]


The act of shutting; a closing; as, the closure of a chink.


That which closes or shuts; that by which separate parts are fastened or closed.

Without a seal, wafer, or any closure whatever. Pope.


That which incloses or confines; an inclosure.

O thou bloody prison . . . Within the guilty closure of thy walls Richard the Second here was hacked to death. Shak.


A conclusion; an end.



5. Parliamentary Practice

A method of putting an end to debate and securing an immediate vote upon a measure before a legislative body. It is similar in effect to the previous question. It was first introduced into the British House of Commons in 1882. The French word cloture was originally applied to this proceeding.


© Webster 1913.

Log in or register to write something here or to contact authors.