Hello,
On Monday, June 20, 2016 at 5:38:04 PM UTC+2, Stefan Karpinski wrote:
>
> The reason as Cedric points out is that the do block syntax is just sugar
> for an anonymous function body. There is a plan to provide a more
> convenient mechanism for ensuring finalization: #7721
> <https://www.google.com/url?q=https%3A%2F%2Fgithub.com%2FJuliaLang%2Fjulia%2Fissues%2F7721&sa=D&sntz=1&usg=AFQjCNFvIk415gxqk8bmc7yh5IjJ917dkQ>.
>
> So, pending syntax debating, you'd write this instead:
>
> Thanks for the link, I recall I had stumbled upon the discussion a while
ago
> fd = open(file)!
> a = read(fd, ...)
> b = read(fd, ...)
> # finalize(fd) called when the scope ends
>
>
> That would be great, also for simultaneous reading/writing of multiple
files as you wrote in the discussion.
> This would significantly reduce the number of situations where the do
> block syntax is used for straight-line code, which I think largely
> eliminates this issue.
>
> I believe in Python (which I only started using after Julia) you can say
with open("one") as one, open("two", "w") as two:
Cheers,
---david
>
> On Mon, Jun 20, 2016 at 10:35 AM, Cedric St-Jean <[email protected]
> <javascript:>> wrote:
>
>> I'm not sure why assignments are local, but I'd guess that it's for
>> consistency. function foo(x, y) ... end is syntactic sugar for foo =
>> (x,y)->..., and likewise do syntax is also sugar for creating a function
>> and passing it as the first argument. Since
>>
>> function foo(x)
>> a = x
>> end
>>
>> does not modify foo's parent scope (the global scope), it seems
>> reasonable that local functions (do blocks) shouldn't modify their parent
>> scope either. Here are other ways of writing the code you quoted:
>>
>> local a, b
>> open(file) do fd
>> a = read(fd, ...) # will modify a and b in the parent scope
>> b = read(fd, ...)
>> end
>>
>> comprehension = map(collection) do i
>> ## compute element[i]
>> element
>> end
>>
>> Best,
>>
>> Cédric
>>
>>
>> On Monday, June 20, 2016 at 7:54:10 AM UTC-4, David van Leeuwen wrote:
>>>
>>> Hello,
>>>
>>> I regularly make the mistake described here
>>> https://groups.google.com/d/msg/julia-users/UyCSm5Shyww/Udt67boT3CsJ,
>>> i.e., i write
>>>
>>> open(file) do fd
>>> a = read(fd, ...)
>>> b = read(fd, ...)
>>> end
>>> ## a and b undefined.
>>>
>>> I get that the solution is
>>>
>>> a, b = open(file) do fd
>>> ...
>>>
>>> Great. I understand that you would want `fd` to be local, is this the
>>> reason that every assignment is local?
>>>
>>> If `a, b = open() do ... end` is the recommended way of dealing with
>>> this, I wonder if this approach could generalize to the for-block
>>>
>>> comprehension = for i in collection
>>> ## compute element[i]
>>> element
>>> end
>>>
>>> as a multiline alternative to the [element for i in collection] syntax.
>>>
>>> Cheers,
>>>
>>> ---david
>>>
>>
>