BREAK and CONTINUE propagation


#1

Have you ever been inside a nested loop and wanted to BREAK or CONTINUE the outer loop…not the inner one you’re presently iterating?

 for-each x data [ // outer loop
     for-each y data [ // inner loop
          if some-test [
              break // !!! want this to break outer loop, d'oh
          ]
          ...
     ]
     ...
 ]

Well you’re in luck :four_leaf_clover: …thanks to the “simple magic” loop result protocol, you have an answer.

 for-each x data [
     for-each y data [
          if some-test [
              break
          ]
          ...
     ] else [break]
     ...
 ]

If you read the details, ELSE will run if-and-only-if the loop breaks. So you can feel confident putting the second BREAK in there.

What if you had wanted to CONTINUE the outer loop instead? Well, all you need to do there is break the inner loop and use that signal to continue the outer loop.

 for-each x data [
     for-each y data [
          if some-test [
              break // in order to continue outer loop
          ]
          ...
     ] else [continue] // ta-da!
     ...
 ]

Pretty sweet, eh? And don’t miss out on how you can use OR to test for either a BREAK -or- the loop body never running due to absence of data or iterations, which comes in handy quite often.


#2

Sweet! I write loops inside loops all the time (which is probably a code smell), so this should lead to some great new flexibility. Keep 'em coming, Brian!


#3

It’s something you have to do…but this is a way of dealing with the scoping of BREAKs and CONTINUEs that doesn’t require GOTO, which is pretty much what you’ve got in C unless you start invoking and maintaining temporary variables.

One thing on the horizon with virtual binding (which I know seems to get deferred a lot, but I do think about it frequently) is the idea that it will be cheap enough to do definitional BREAK and CONTINUE, which know which loops they break.

 for-each a outer [
     outer-break: :break
     for-each b inner [
         if some-condition [outer-break]
     ]
 ]

This may still come down the road, but it is still rather GOTO-like, so I think if you can avoid it you get a better “structured programming” answer sticking to the loop result protocol.