Unless I'm mistaken, this is a consequence of lexical scoping. See the 
fifth paragraph down 
http://docs.julialang.org/en/latest/manual/variables-and-scoping/.

Since mesh() is defined inside of foo(), the call to `mesh(2:3) in the line 
`y = mesh(2:3)` actually reassigns the name `x` from the line above to 
`repmat(2:3.', 2, 1)`. This is because after `x` is defined in the previous 
line, it is a valid name that the scope of `mesh` inherits.

Note that if wrap the `x` assignment in a `let` block, trying to return `x` 
incurs an error:

julia> function foo() 
    mesh(y) = (x = repmat(y.', 2, 1); return x) 
    let x = mesh(1:2) end 
    y = mesh(2:3) # <- this line is necessary to see the effect 
    return x 
 end 
foo (generic function with 1 method) 

julia> foo() 
ERROR: UndefVarError: x not defined 
in foo at none:5

In the above case, the `let` block introduces a new local scope that is not 
inheritable by `mesh`. The `x` variable within `mesh`'s body is then 
contained entirely within `mesh`'s scope and inaccessible to `foo`'s, hence 
the error.


On Wednesday, July 15, 2015 at 2:40:17 PM UTC-4, Ethan Anderes wrote:
>
> Hi Everyone. I hope this isn’t a stupid question but I can’t seem to 
> understand the following
> scoping behavior. The basic story is that mesh in the following two 
> examples behaves differently when defined in global scope vrs within a 
> function. I’m worried that I’m completely ignorant of how functions work 
> within other functions. Some help would be much appreciated. Thanks!
>
> In this block of code mesh is defined as a global variable.
>
> julia> mesh(y) = (x = repmat(y.', 2, 1); return x)
> mesh (generic function with 1 method)
>
> julia> x = mesh(1:2);
>
> julia> y = mesh(2:3);
>
> julia> x
> 2x2 Array{Int64,2}:
>  1  2
>  1  2
>
> When I quit, restart Julia and define mesh within foo I get a different 
> answer.
>
> julia> function foo()
>             mesh(y) = (x = repmat(y.', 2, 1); return x)
>             x = mesh(1:2)
>             y = mesh(2:3) # <- this line is necessary to see the effect
>             return x
>         end
> foo (generic function with 1 method)
>
> julia> x = foo()  # <- different than the x in the global case.
> 2x2 Array{Int64,2}:
>  2  3
>  2  3
>
> Here is my version info
>
> julia> versioninfo()
> Julia Version 0.4.0-dev+5994
> Commit 8efc44d (2015-07-15 15:42 UTC)
> Platform Info:
>   System: Darwin (x86_64-apple-darwin14.4.0)
>   CPU: Intel(R) Core(TM) M-5Y51 CPU @ 1.10GHz
>   WORD_SIZE: 64
>   BLAS: libopenblas (USE64BITINT NO_AFFINITY HASWELL)
>   LAPACK: libopenblas
>   LIBM: libopenlibm
>   LLVM: libLLVM-3.3
>
> ​
>

Reply via email to