为什么/如何确定函数何时覆盖 Julia 中的局部变量?

use*_*237 12 scope julia

我对 Julia 比较陌生,正在移植一些 C 函数来检查速度差异。我正在努力解决的一个问题是变量的范围。具体来说,有时 Julia 中的函数调用会覆盖局部变量,而有时不会。例如,这是一个计算最小生成树的函数:

function mst(my_X::Array{Float64})
    n = size(my_X)[1]
    N = zeros(Int16,n,n)
    tree = []
    lv = maximum(my_X)+1
    my_X[diagind(my_X)] .=lv
    indexi = 1
    for ijk in 1:(n-1)
        tree = vcat(tree, indexi)
        m = minimum(my_X[:,tree],dims = 1)
        a = zeros(Int64, length(tree))
        print(tree)
        for k in 1:length(tree)
            a[k] = sortperm(my_X[:,tree[k]])[1,]
        end
        b = sortperm(vec(m))[1]
        indexj = tree[b]
        indexi = a[b]
        N[indexi,indexj] = 1
        N[indexj,indexi] = 1
        for j in tree
            my_X[indexi,j] = lv
            my_X[j,indexi] = lv
        end
    end
    return N
end
Run Code Online (Sandbox Code Playgroud)

现在我们可以将其应用于距离矩阵X

julia> X
5×5 Array{Float64,2}:
 0.0   0.54  1.08  1.12  0.95
 0.54  0.0   0.84  0.67  1.05
 1.08  0.84  0.0   0.86  1.14
 1.12  0.67  0.86  0.0   1.2
 0.95  1.05  1.14  1.2   0.0
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,它会覆盖所有的条目 X

julia> M = mst(X)
julia> M
5×5 Array{Int16,2}:
 0  1  0  0  1
 1  0  1  1  0
 0  1  0  0  0
 0  1  0  0  0
 1  0  0  0  0
julia> X
5×5 Array{Float64,2}:
 2.2  2.2  2.2  2.2  2.2
 2.2  2.2  2.2  2.2  2.2
 2.2  2.2  2.2  2.2  2.2
 2.2  2.2  2.2  2.2  2.2
 2.2  2.2  2.2  2.2  2.2
Run Code Online (Sandbox Code Playgroud)

当然,如果我在函数中明确地放置这样的东西,我可以覆盖它:

function mst(my_Z::Array{Float64})
    my_X = copy(my_Z)
     .
     .
     .
Run Code Online (Sandbox Code Playgroud)

但问题似乎比这更深刻。例如,如果我尝试在一个简单的示例中复制它,则无法重现该问题:

function add_one(my_X::Int64)
    my_X = my_X + 1
    return my_X
end
Run Code Online (Sandbox Code Playgroud)
julia> Z = 1
julia> W = add_one(Z)
julia> W
2
julia> Z
1
Run Code Online (Sandbox Code Playgroud)

这里发生了什么??我已经阅读并重新阅读了有关变量作用域的 julia 帮助文档,但我无法弄清楚两者之间的区别。

Bog*_*ski 12

这里有以下相互关联的问题:

  1. Julia 中的值可以是可变的,也可以是不可变的。
  2. Julia 中的变量绑定到一个值(可以是不可变的或可变的)。
  3. 一些操作可以修改可变值。

所以第一点是关于值的可变性与不变性。此处给出了 Julia 手册中的讨论。您可以使用isimmutable函数检查值是否可变。

典型案例如下:

  1. 数字、字符串、TupleNamedTuplestructs 是不可变的
julia> isimmutable(1)
true

julia> isimmutable("sdaf")
false

julia> isimmutable((1,2,3))
true
Run Code Online (Sandbox Code Playgroud)
  1. 数组、字典mutable structs等(通常是Tuple,NamedTuplestructs以外的容器类型)是可变的:
julia> isimmutable([1,2,3])
false

julia> isimmutable(Dict(1=>2))
false
Run Code Online (Sandbox Code Playgroud)

不可变值和可变值之间的主要区别在于可变值可以修改其内容。这是一个简单的例子:

julia> x = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> x[1] = 10
10

julia> x
3-element Array{Int64,1}:
 10
  2
  3
Run Code Online (Sandbox Code Playgroud)

现在让我们剖析一下我们在这里看到的:

  • 赋值语句x = [1, 2, 3]将值(在本例中为向量)绑定到变量x
  • 该语句x[1] = 10在适当的位置改变值(向量)

请注意,对于 aTuple来说同样会失败,因为它是不可变的:

julia> x = (1,2,3)
(1, 2, 3)

julia> x[1] = 10
ERROR: MethodError: no method matching setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64)
Run Code Online (Sandbox Code Playgroud)

现在我们来到第二点 - 将一个值绑定到一个变量名。这通常是使用=运算符完成的,如果在它的左侧我们看到一个像上面那样的变量名x = [1,2,3]x = (1,2,3)

请注意,特别是+=(和类似的)正在重新绑定,例如:

julia> x = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> y = x
3-element Array{Int64,1}:
 1
 2
 3

julia> x += [1,2,3]
3-element Array{Int64,1}:
 2
 4
 6

julia> x
3-element Array{Int64,1}:
 2
 4
 6

julia> y
3-element Array{Int64,1}:
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)

因为在这种情况下它只是 的简写x = x + [1, 2, 3],我们知道它会=重新绑定。

特别是(如@pszufe 在评论中指出的),如果您将值传递给函数,则不会复制任何内容。这里发生的是函数签名中的变量绑定到传递的值(这种行为有时称为pass by sharing)。所以你有了:

julia> x = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> f(y) = y
f (generic function with 1 method)

julia> f(x) === x
true
Run Code Online (Sandbox Code Playgroud)

基本上发生的事情是“好像”你写了y = x. 不同之处在于函数y在新的作用域(函数的作用域)中创建一个变量,而y = x将创建x绑定到y语句所在作用域中的变量的值的绑定y = x

另一方面,例如x[1] = 10(本质上是一个setindex!函数应用程序)或x .= [1,2,3]就地操作(它们不重新绑定值,而是尝试改变容器)。所以这可以就地工作(请注意,在示例中,我将广播与组合在一起+=以使其就位):

julia> x = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> y = x
3-element Array{Int64,1}:
 1
 2
 3

julia> x .+= [1,2,3]
3-element Array{Int64,1}:
 2
 4
 6

julia> y
3-element Array{Int64,1}:
 2
 4
 6
Run Code Online (Sandbox Code Playgroud)

但是如果我们尝试对例如做同样的事情。一个不可变的整数,操作将失败:

julia> x = 10
10

julia> x .+= 1
ERROR: MethodError: no method matching copyto!(::Int64, ::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{0},Tuple{},typeof(+),Tuple{Int64,Int64}})
Run Code Online (Sandbox Code Playgroud)

与为不可变值设置索引相同:

julia> x = 10
10

julia> x[] = 1
ERROR: MethodError: no method matching setindex!(::Int64, ::Int64)
Run Code Online (Sandbox Code Playgroud)

最后,第三件事是哪些操作试图就地改变值。我们已经注意到其中的一些(例如setindex!:x[10] = 10和广播分配x .= [1,2,3])。一般来说,如果是某个通用函数(如果是可变的,它可能会或可能不会发生变化),决定调用f(x)是否会发生变化并不总是那么容易。因此,在 Julia 中有一个约定在函数名称的末尾添加,这些函数可能会改变它们的参数以直观地表示这一点(应该强调的是,这只是一个约定——特别是在函数名称的末尾添加函数对其工作方式没有直接影响)。我们已经看到了(它的速记是xfxx!!setindex!x[1] = 10 如上所述),但这里有一个不同的例子:

julia> x = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> filter(==(1), x) # no ! so a new vector is created
1-element Array{Int64,1}:
 1

julia> x
3-element Array{Int64,1}:
 1
 2
 3

julia> filter!(==(1), x) # ! so x is mutated in place
1-element Array{Int64,1}:
 1

julia> x
1-element Array{Int64,1}:
 1
Run Code Online (Sandbox Code Playgroud)

如果您使用的函数(如setindex!)会对其参数进行变异,并希望在向其copy传递参数时避免使用变异(或者deepcopy如果您的结构是多重嵌套的,并且可能会在更深层次上发生变异 - 但这种情况很少见)。

所以在我们的例子中:

julia> x = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> y = filter!(==(1), copy(x))
1-element Array{Int64,1}:
 1

julia> y
1-element Array{Int64,1}:
 1

julia> x
3-element Array{Int64,1}:
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案!我可能会强调“!”不会导致函数发生变异(你不是这么说的,但如果浏览的话很容易误读,而且我见过几个人在这种误解下工作。) (2认同)