Julia - Continue outer loop
Asked Answered
E

3

7

I am currently porting an algorithm from Java to Julia and now I have come across a part where I have to continue an outer loop from an inner loop when some condition is met:

 loopC: for(int x : Y){
            for(int i: I){
                if(some_condition(i)){
                    continue loopC;
                }                   
            }
        }

I have found some issues on GitHub on this topic but there seems to be only a discussion about it and no solution yet. Does anybody know a way how to accomplish this in Julia?

Eph answered 7/11, 2016 at 15:39 Comment(0)
G
6

As in some other languages julia uses break for this:

for i in 1:4
    for j in 1:4
        if j == 2
            break
        end
    end
end

breaks out of the inner loop whenever j is 2

However, if you ever need to exit the outer loop you can use @goto and @label like so

for i in 1:4
    for j in 1:4
        if (j-i) == 2
            @goto label1
        end 

        if j == 2 
            @goto label2
        end 
        do stuff
    end 
    @label label2
end 
@label label1

Straight from the julia docs http://docs.julialang.org/en/release-0.5/manual/control-flow/

It is sometimes convenient to terminate the repetition of a while before the test condition is falsified or stop iterating in a for loop before the end of the iterable object is reached. This can be accomplished with the break keyword

Glebe answered 7/11, 2016 at 16:7 Comment(1)
This works! But the link no longer works, and this method of doing things is no longer in the docs.Palmitate
N
2

As mentioned by @isebarn, break can be used to exit the inner loop:

for i in 1:3
    for j in 1:3
        if j == 2
            break # continues with next i
        end  
        @show (i,j)  
    end # next j  
end # next i   
(i, j) = (1, 1)
(i, j) = (2, 1)
(i, j) = (3, 1)

However, some caution is required because the behaviour of break depends on how the nested loops are specified:

for i in 1:3, j in 1:3
    if j == 2
        break # exits both loops
    end  
    @show (i,j)  
end # next i,j   
(i, j) = (1, 1)  

See https://en.wikibooks.org/wiki/Introducing_Julia/Controlling_the_flow#Nested_loops

It is also possible, albeit cumbersome, to return from a nested function that contains the inner loop:

for i in 1:3  
    (i -> for j in 1:3  
         if j == 2  
             return  
         end  
         @show (i,j)  
    end)(i)
end  
(i, j) = (1, 1)
(i, j) = (2, 1)
(i, j) = (3, 1)
Nemato answered 23/6, 2019 at 21:4 Comment(0)
L
0

This can be achieved using flags:

for i in 1:3  
    flag = false
    for j in 1:3  
         if j == 2  # some condition
             flag = true
             break
         end  
    end
    if flag
        continue
    end
    #...
end  
Loadstone answered 18/9 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.