Subtle scope differences

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Subtle scope differences

David van Leeuwen
Hello, 

Of these three functions, the second raises a UndefVarError. 

a = rand(10)

function scope1(i)
   
return a[i]
end

## fails
function scope2(i)
    a
= a[i] ## fails here: `a` not defined.  The `a =` makes `a` local, and undefines the global `a`
   
return a
end

function scope3(a, i)
    a
= a[i]
   
return a
end

println
(scope1([2, 5]))
println
(scope2([2, 5]))
println
(scope3(a, [2, 5]))

I've read up on the section in the manual, but the case in `scope2()` is not covered I believe.  I wonder if what happens in `scope2()` is intended behaviour. 

---david

Background:

I find myself often using the pattern 

x = x[slice]

for (temporarily) working on a subset of the data.  It is handy to do that in functions, because the arrays automatically get re-bound in a local scope.   With many of these variables, it is convenient to inherent them from a global scope, rather than adding them as function arguments. 
Reply | Threaded
Open this post in threaded view
|

Re: Subtle scope differences

Yichao Yu
On Thu, Mar 24, 2016 at 4:00 AM, David van Leeuwen
<[hidden email]> wrote:

> Hello,
>
> Of these three functions, the second raises a UndefVarError.
>
> a = rand(10)
>
> function scope1(i)
>     return a[i]
> end
>
> ## fails
> function scope2(i)
>     a = a[i] ## fails here: `a` not defined.  The `a =` makes `a` local, and
> undefines the global `a`

a is either global or local, it never changes.

>     return a
> end
>
> function scope3(a, i)
>     a = a[i]
>     return a
> end
>
> println(scope1([2, 5]))
> println(scope2([2, 5]))
> println(scope3(a, [2, 5]))
>
> I've read up on the section in the manual, but the case in `scope2()` is not
> covered I believe.  I wonder if what happens in `scope2()` is intended
> behaviour.
>
> ---david
>
> Background:
>
> I find myself often using the pattern
>
> x = x[slice]

Don't do this. For one thing, you introduce type instablity.

>
> for (temporarily) working on a subset of the data.  It is handy to do that
> in functions, because the arrays automatically get re-bound in a local
> scope.   With many of these variables, it is convenient to inherent them
> from a global scope, rather than adding them as function arguments.
Reply | Threaded
Open this post in threaded view
|

Subtle scope differences

Matt Bauman
In reply to this post by David van Leeuwen
This case could definitely be emphasized further in the manual. The key is that assigning to a variable makes that name local within a hard scope... regardless of whether that assignment happens before or after the first access.