Julia 在for循环中重复使用的多个输出
我使用的是Julia,我设计了一个for循环,它在一个循环中获取函数的输出,并在下一个循环中使用它们作为该函数的输入(一次又一次)。当我运行这段代码时,Julia会标记一个“未定义”错误,但是,如果我在调试模式下运行代码,它会完美地执行。例如,代码如下所示:Julia 在for循环中重复使用的多个输出,julia,Julia,我使用的是Julia,我设计了一个for循环,它在一个循环中获取函数的输出,并在下一个循环中使用它们作为该函数的输入(一次又一次)。当我运行这段代码时,Julia会标记一个“未定义”错误,但是,如果我在调试模式下运行代码,它会完美地执行。例如,代码如下所示: function do_command(a,b,c,d) a = a + 1 b = split(b, keepempty=false)[1] c = split(b, keepempty=false)[1] if
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
for ii in 1:length(x)
if ii == 1
a = 0
b = "string something"
c = ""
d = false
end
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
# Let's create a local scope: it's good practice to avoid global variables
let
# All these variables are declared in the scope introduced by `let`
a = 0
b = "string something"
c = ""
d = false
for ii in 1:10 #length(x)
# now these names refer to the variables declared in the enclosing scope
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
end
我做错了什么?您的代码的一个问题是
for
为循环的每个迭代引入了一个新的范围。也就是说:在迭代1时在循环体中创建的变量a
与在迭代2时在循环体中创建的变量a
不同
为了解决您的问题,您应该在循环外部声明变量,以便在每次迭代中,从循环体中对它们的引用实际上会引用封闭范围中的相同变量
我会这样说:
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
for ii in 1:length(x)
if ii == 1
a = 0
b = "string something"
c = ""
d = false
end
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
# Let's create a local scope: it's good practice to avoid global variables
let
# All these variables are declared in the scope introduced by `let`
a = 0
b = "string something"
c = ""
d = false
for ii in 1:10 #length(x)
# now these names refer to the variables declared in the enclosing scope
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
end
您的示例中缺少了
x
,但我想这只是一个拷贝粘贴问题,而不是您真正的问题。。。