views:

332

answers:

4

I've found that lots of people use the words closure and block interchangeably. Most of these people can't explain what they're talking about.

Some Java programmers (even ones from really expensive consultancies) talk about anonymous inner classes as "blocks" and "closures" - but I know this isn't true. (You can't pass mutable variables in from the scope of the method in which they're defined...)

I'm looking for:

  • a precise, computer science definition of a block
  • a precise, computer science definition of a closure
  • and clarification on the difference between the two.

I'd really like to see links, articles or book references on these please.

+3  A: 

While a block is just a piece of code that can be composed by statements and declarations but nothing else, a closure is a real first-class object, a real variable that has a block as its value.

The main difference is that a block simply groups instructions together (for example the body of a while statement), while a closure is a variable that contains some code that can be executed.

If you have a closure usually you can pass it as a parameter to functions, currify and decurrify it, and mainly call it!

Closure c = { println 'Hello!' }
/* now you have an object that contains code */
c.call()

Of course closures are more powerful, they are variables and can be used to define custom behaviour of objects (while usually you had to use interfaces or other OOP approaches in programming).

You can think of a closure as a function that contains what that function does inside itself.

Blocks are useful because they allow scoping of variables. Usually when you define a variable inside a scope you can override the outer definitions without any problems and new definitions will exist just during the execution of block.

for (int i = 0; i < 10; ++i)
{
     int t = i*2;
     printf("%d\r\n", t);
}

t is defined inside the block (the body of the for statement) and will last just inside that block.

Jack
a block also marks the begin-end of an "object scope".
jldupont
you are right, forgot to mention that.. just updated
Jack
+5  A: 

A block is something syntactical - A logical unit of statements (more related to scope than to closure).

if (Condition) {
    // Block here 
} 
else {
    // Another block
}

A closure is related to anoymous functions or classes - An anonymous (function) object, a piece of code that is bound to an environment (with its variables).

def foo() {
   var x = 0
   return () => { x += 1; return x }
}

Here foo returns a closure! The local variable x persists through the closure even after foo terminated and can be incremented through calls of the returned anonymous function.

val counter = foo()
print counter() // Returns 2
print counter() // Return 3

Note that's just Ruby in which block and closure are treated similarly since what Ruby calls block is a closure:

(1..10).each do |x|
    p x
end

There each-method is passed a closure function (taking a parameter x) which is called a block in Ruby.

Dario
... then there's the confusion with Smalltalk. What Ruby programmers call a block, Smalltalk calls a `BlockClosure`!
cartoonfox
Actually, in your Ruby example, the block is *not* a closure, because it doesn't close over anything. More interesting would be `a = 7; (1..10).each do |x| p a << x end` or something like that.
Jörg W Mittag
A: 

The terms you are using are most commonly used together these days in Ruby, although the constructs previously appeared in Algol, Smalltalk, and Scheme. I would quote the Ruby standard, if there was one.

I'm not sure I'm able to answer your exact question, but I can illustrate. My apologies if you know this already...

def f &x
  yield
  x
end

def g
  y = "block"
  t = f { p "I'm a #{y}" }
  y = "closure"
  t
end

t = g
t.call

And...

$ ruby exam.rb
"I'm a block"
"I'm a closure"
$

So a block is an anonymous function-like sequence of code attached to a method call. It's used all over the Ruby API. When you make it easy enough to create an anonymous function it turns out they are useful for all kinds of things.

But note that after f returns, then g returns, we held on to the block by returning it from f (as x) and then from g (as t). Now we call the block a second time. Again, note that g() has returned. But the block refers to a local variable in a function instance (and scope) that doesn't exist any more?! And it gets the new value of y?!

So a closure is a function-like object that is closed over its lexical scope. They are quite challenging to implement because they destroy the do-it-with-a-stack model that is so useful for local variables in function call instances.


1. Ruby has various flavors of closure-like function objects; this is just one of them.

DigitalRoss
A: 

The loud, bearded one has this to say about Closures and Blocks:

http://martinfowler.com/bliki/Closure.html

At one point he says a closure is a block that can be passed as an argument to a method.

cartoonfox