[Newbies] Closure support
andy.burnett at knowinnovation.com
Fri Oct 30 15:59:16 UTC 2009
<<With classic smalltalk 80 and Squeak:
a := (1 to: 10) do: [:n | [n]].
b := a collect: [:each | each value].
b will have something like #(10 10 10 10 ...).
The problem is that the :n in each block ([n]) is shared as one variable.
In a true closure, which modern Squeak and Pharo provide, we get the proper
#(1 2 3 4 ... 10). That's because each apperance of "n" is "closed" with
respect to the newly created block.>>
Thanks for explaining the difference between blocks and closures. I think I
new understand that. And, your example raised a new question for me.
What does the inner 'block' in [:n | [n]] actually do?
Out of curiosity I tried changing it to [:n | [n*10]], expecting the numbers
to be ten times bigger, but they were stil 1, 2, 3... I also tried removing
the whole block, and b still evaluated to the same values.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners