Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - Continue outer loop

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?

like image 487
DP. Avatar asked Nov 07 '16 15:11

DP.


2 Answers

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

like image 51
isebarn Avatar answered Nov 03 '22 01:11

isebarn


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)
like image 45
Tom Price Avatar answered Nov 03 '22 01:11

Tom Price