朱莉娅做任务奇怪的事情

Ali*_*Ali 1 debugging julia

我试图通过重复Julia中一些简单的ProjectEuler问题来学习Julia.到目前为止,一切都非常顺利,直到我遇到这个令人沮丧的问题.我花了一些时间调试我的代码,这就是我发现的:(希望我不会错过这里真正愚蠢的东西)

function is_abundant(n::Int)                        #just a function
    return prod(map(x->int((x[1]^(x[2]+1)-1)/(x[1]-1)),factor(n))) > 2 * n
end

abundants=[12]     #there should be a better way to initialize an Array
for i=13:28120
    if is_abundant(i)
        push!(abundants,i)
    end
end

le=abundants;      #The following lines are the problems
ri=abundants;
d=length(abundants)
println(d)
pop!(le)
shift!(ri)
println(le==ri, " ", endof(ri), " ", endof(abundants))
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

6964 true 6962 6962

这意味着朱莉娅改变了所有三组le,ri并且abundants每个pop!shift!命令都改变了.我能够通过使用一个愚蠢的额外身份映射来解决这个bug /问题:

le=map(x->x,abundants)
ri=map(x->x,abundants)
Run Code Online (Sandbox Code Playgroud)

现在输出会改变到我最初的预期:

6964 false 6963 6964

我的问题是,如果这不是一个错误,为什么朱莉娅保持一个等价关系le,riabundants设置在第一位?此外,任何人都可以重现这种行为吗?我在Ubuntu 14.04上使用Julia"Version 0.3.0-rc3 + 14(2014-08-13 16:01 UTC)".

Iai*_*ing 5

le并且ri两者都指向指向的相同列表abundants,因此这是预期的行为 - 它们都在相同的内存上运行.本手册的这一部分可能有助于您理解.或者可能是MATLAB差异部分,因为它在MATLAB中是不同的(但大多数其他语言都像Julia).

对于

abundants=[12] #there should be a better way to initialize an Array
Run Code Online (Sandbox Code Playgroud)

怎么样

abundants = {}  # Vector of anything
Run Code Online (Sandbox Code Playgroud)

要么

abundants = Int[]  # Vector of ints
Run Code Online (Sandbox Code Playgroud)

而不是你map(x->x,...),你可以使用copy.