Randal said...
<<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.
Cheers Andy
"Andy" == Andy Burnett andy.burnett@knowinnovation.com writes:
Andy> Randal said... Andy> <<With classic smalltalk 80 and Squeak:
Andy> a := (1 to: 10) do: [:n | [n]]. Andy> b := a collect: [:each | each value]. Andy> b will have something like #(10 10 10 10 ...).
Argh. That should have been collect: not do:
Andy> Out of curiosity I tried changing it to [:n | [n*10]], expecting the numbers Andy> to be ten times bigger, but they were stil 1, 2, 3... I also tried removing Andy> the whole block, and b still evaluated to the same values.
Works better with collect. :)
a := (1 to: 10) collect: [:n | [n * 10]]. b := a collect: [:each | each value]
b is now #(10 20 30 40 50 60 70 80 90 100) in a closure world. In non-closure, it would have been 100, 100, 100...
On Friday 30 October 2009 09:29:16 pm Andy Burnett wrote:
What does the inner 'block' in [:n | [n]] actually do?
A block is just a list of bytecodes - an anonymous method. When the 'value' message is sent to a block, the list is evaluated and the result is returned. In this case, the value of n (or n*10 in your second example).
HTH .. Subbu
beginners@lists.squeakfoundation.org