[squeak-dev] Variable capture in block closure
Tony Garnock-Jones
tonyg at leastfixedpoint.com
Mon Jan 21 18:10:44 UTC 2019
Hi Stef,
On 1/21/19 5:47 PM, Stéphane Rollandin wrote:
> Is it expected that
>
> | blocks x |
> blocks := OrderedCollection new.
> (1 to: 3) do: [:n |
> x := n.
> blocks add: [Transcript showln: x]].
> blocks do: #value
>
> prints 3 three times, while
>
> | blocks |
> blocks := OrderedCollection new.
> (1 to: 3) do: [:n |
> | x |
> x := n.
> blocks add: [Transcript showln: x]].
> blocks do: #value
>
> prints 1, 2, 3 ?
I would expect to see that, yes. I expect the first snippet to update a
single `x`-variable, while the second snippet creates (and then
immediately updates) a fresh `x`-variable within the scope of each
execution of the block argument to `#do:`.
I'd also expect
| blocks |
blocks := OrderedCollection new.
(1 to: 3) do: [:n | blocks add: [Transcript showln: n]].
blocks do: #value
to print 1, 2, 3, since I would expect a fresh `n` for each invocation
of the `#do:` block.
But then my mind has been poisoned by decades of exposure to high levels
of ambient Scheme.
Regards,
Tony
More information about the Squeak-dev
mailing list
|