茱莉亚全局变量定义在 let 块



>我有以下朱莉娅函数

function fakeseq()
    let; global f(x)=unshift!(push!(x, 35) , 1);end; # not working
    #let; global f; f=x->unshift!(push!(x, 35) , 1);end; # works fine
    s1 = [rand(1:34) for i in 1:12]; 
    s2 = [rand(1:34) for i in 1:7]
    data = map(x->f(x), [s1, s2])
end

当我运行该代码时,出现以下错误:

julia> fakeseq()
   ERROR: MethodError: no method matching f(::Array{Int64,1})
   The applicable method may be too new: running in world age 21823, while current world is 21824.
   Closest candidates are:        f(::Any) at REPL[1]:2 (method too new to be called from this world context.)
   Stacktrace:
   [1] _collect(::Array{Array{Int64,1},1}, 
   ::Base.Generator{Array{Array{Int64,1},1},##3#6}, ::Base.EltypeUnknown, 
   ::Base.HasShape) at ./array.jl:488
   [2] fakeseq() at ./REPL[1]:6

但是,用# works fine注释指示的f的第二个定义有效。我无法理解它们之间的确切区别,为什么会这样?

正如@AlexanderMorley指出的,你需要浏览一下

https://docs.julialang.org/en/latest/manual/methods.html#Redefining-Methods-1

或观看詹姆森的Youtube视频:

https://www.youtube.com/watch?v=7KGZ_9D_DbI

泛型函数的处理方式与 Julia 中的匿名函数略有不同。在泛型函数的情况下,发生的事情是这样的,程序编译知道全局函数表中f是什么,你修改f,但调用函数已经编译为调用不再是正确函数的内容,因此它出错了。错误是停止问题 #265。不过,匿名函数是不同的。在匿名函数的情况下,调用函数设置为调用该变量指向的任何函数。在这种情况下,它知道它也是一个全局变量,所以它是安全的,并且不会内联它或类似的东西,所以它是成功的。

相关内容

最新更新