如何在Julia中打破嵌套的for循环

时间:2016-09-30 16:38:33

标签: julia nested-loops

我试图以一种非常无效的方式打破嵌套循环:

VideoWidgetView

有更简单的方法吗?在我的实际问题中,除了它们是BreakingPoint = false a=["R1","R2","R3"] b=["R2","R3","R4"] for i in a for j in b if i == j BreakingPoint = true println("i = $i, j = $j.") end if BreakingPoint == true; break; end end if BreakingPoint == true; break; end end 之外,我不知道数组ab中的内容。数组名称(示例代码中的ASCIIStringa)也是通过元编程方法自动生成的。

2 个答案:

答案 0 :(得分:12)

你可以做两件事之一

在多外循环

中有循环语句(如果那就是它的名字)
const U = f => f (f);
const Y = U (h => f => f (x => h (h) (f) (x)));

const lt = x => y => y < x;
const gt = x => y => y > x;
const add1 = x => x + 1;
const sub1 = x => x - 1;

const range = Y (f => acc => x => p => t =>
  p(x) ? f ([...acc, x]) (t(x)) (p) (t) : acc 
) ([]);

console.log(range (3) (lt(6)) (add1)); // [3,4,5]
console.log(range (6) (lt(6)) (add1)); // []
console.log(range (9) (gt(6)) (sub1)); // [9,8,7]

这是干净的,但并非总是可能

我会被钉死在十字架上,但你可以使用@goto和@label

for i in a, j in b
    if i == j
        break
    end 
end 

如果您使用@ goto / @标签方式,为了维护/审查代码的人,请正确记录您的使用情况,因为带标签的导航代码令人叹为观止

有关多循环中断的讨论,请参阅this

答案 1 :(得分:9)

将2D循环放入函数中,并在需要return时进行早期break