> Ahhh, the closure explanation makes sense Mauro. I have used closures 
> before but my shared state variables were always arrays which were mutated 
> inplace so the closure scoping behavior acted just like the global scoping 
> rules.

Yes, in that case the variable is read-only as the binding of the
variable stays unchanged.  Probably worth mentioning in the docs too.

> I can now see that people would want similar behavior for non-arrays and 
> non-mutating operations on the local state. In particular, the following 
> closure works like the above closure but for Numbers.
>
> julia> function makeclosure{T<:Number}(state::T)
>            function updatestate()
>                state += 1
>            end
>            function printstate()
>                println(state)
>            end
>            return updatestate::Function, printstate::Function
>        end
> makeclosure (generic function with 2 methods)
>
> julia> u2, p2 = makeclosure(1)
> (updatestate,printstate)
>
> julia> p2()
> 1
>
> julia> u2()
> 2
>
> julia> p2()
> 2
>
> Of course, now the scoping behavior within makeclosure conflicts with the 
> global REPL behavior.

It does follow the rules spelt out in the updated docs as `state` is a
local variable.  But yes, it can be confusing.  An alternative is
described here:
https://github.com/JuliaLang/julia/issues/10559
https://github.com/JuliaLang/julia/issues/5331

> I took a look at your updated version of that section in the manual. I like 
> the new example on closures. I have two comments. First, you might want to 
> extend the closure example beyond the let block. Mainly because it wasn’t 
> immediately obvious to me how that let block closure was useful. Second, 
> I’m starting to think that the manual could use a subsection titled 
> “Scoping rules for nested functions” which makes clear that functions 
> within functions have different behavior than functions defined in a module 
> or the REPL.

I did the first suggestion.  Although I'm hesitant to introduce yet
another section.  Although, I did emphasis this behavior a bit more in
the text.

> Thanks for your help Mauro!
>
> BTW: Mauro, feel free to copy, cut, paste and mutate any of the above text 
> if you think it would be useful for your draft of that section of the 
> Manual.

You're welcome and thanks to you! M

> On Thursday, July 16, 2015 at 6:01:36 AM UTC-7, Mauro wrote:
>
>> Question 2) What advantage is there for changing the scoping rules for 
>> > nested functions? 
>>
>> How is this for an explanation: 
>>
>> https://github.com/mauro3/julia/blob/m3/scope-doc/doc/manual/variables-and-scoping.rst#hard-vs-soft-local-scope
>>  
>>
> ​

Reply via email to