[Newbies] Block and Closure
K. K. Subramaniam
subbukk at gmail.com
Fri Apr 10 02:40:30 UTC 2009
On Friday 10 April 2009 3:24:42 am Andrey Larionov wrote:
> What difference between this things. I know about Eliots post
> describing closures in Squeak, but it's too massive and so special to
Briefly, A closure tracks the full computational state of its block.
A block is a executable entity with zero or more parameters. It may also use
variables from an outside scope. The parameters of the block are bound to the
arguments given when the block is evaluated. But what about variables like i
from an outer scope like in the example given by Bert a few weeks back :
multiply := Array new: 4.
1 to: 4 do: [:i |
multiply at: i put: [:x | x * i].
(multiply at: 3) value: 5.
When the block is evaluated, will it have the value it had at the time the
block was created or at the time it was evaluated? The behavior is
unspecified. It is an open question :-).
In Squeak, i in the block will refer to the i in the do: block and the last
statement will print 25 because i would be 5 when do: terminates. A closure
maintains its own store for variables like i. At the time of creation, the
local store is initialized with i. At the time of invocation, i will refer to
this local copy, so the correct value of 15 will be printed.
HTH .. Subbu
More information about the Beginners