[squeak-dev] Variable capture in block closure

Eliot Miranda eliot.miranda at gmail.com
Mon Jan 21 19:48:35 UTC 2019


> On Jan 21, 2019, at 10:10 AM, Tony Garnock-Jones <tonyg at leastfixedpoint.com> wrote:
> 
> 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.

As should
    | blocks |
    blocks := OrderedCollection new.
    1 to: 3 do: [:n | blocks add: [Transcript showln: n]].
    blocks do: #value

and

    ((1 to: 3) collect: [:n | [Transcript showln: n]]) do: #value

> 
> But then my mind has been poisoned by decades of exposure to high levels
> of ambient Scheme.

Purified and elevated ;-)

Closures are closures :-)

> Regards,
>  Tony
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.squeakfoundation.org/pipermail/squeak-dev/attachments/20190121/0ce9ea26/attachment.html>


More information about the Squeak-dev mailing list