In Julia, is there a way to pass a variable from a local scope to the enclosing local scope?

我的梦境 提交于 2021-02-07 19:42:24

问题


I am writing some Julia code, wrapped in a function for performance. I need to pass a variable created in a loop to an outer loop but would like to avoid globals for performance reasons:

function f()
    for i=1:1
        for j=1:1
        a=2
        end
    println(a)
    end
end
f()

This throws an error since the scope of the i-loop does not know about the variable a. Definining a first within the scope in question works:

function f()
    for i=1:1
    a=0
        for j=1:1
        a=2
        end
    println(a)
    end
end
f()

I am not super happy with that solution though, since it requires to pre-define every variable that I want to pass. Is there no direct way to pass the variable to the enclosing scope?


回答1:


I don't think there is a direct way (except global a = 2 what you want to avoid).

The closest to what you want is to use local:

function f()
    for i=1:1
    local a
        for j=1:1
        a=2
        end
    println(a)
    end
end
f()



回答2:


@crstnbr is correct that the feature you are asking about is not directly supported. Nested scopes inherit from their enclosing scopes, not the reverse. This is intended to prevent unintentional pollution of the enclosing scope with variables created within the nested scope.

Your second example function looks a little goofy because it's a toy example, but normally it makes sense to provide an initial value for a variable before you iteratively apply some change to it. For example, consider a function that returns an array containing the first n Fibonacci numbers (starting with 0 as the zeroth Fibonacci number):

# n is an integer greater than 0
function fib(n)
    if n==1
        return [0]
    end

    seq = [0, 1]
    while length(seq) < n
        nxt = seq[end-1] + seq[end]
        push!(seq, nxt)
    end

    seq
end
julia> fib(10)
10-element Array{Int64,1}:
  0
  1
  1
  2
  3
  5
  8
 13
 21
 34

Here you need to provide an initial value for seq before you can iterate over it with seq[end-1] + seq[end].



来源:https://stackoverflow.com/questions/57788621/in-julia-is-there-a-way-to-pass-a-variable-from-a-local-scope-to-the-enclosing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!