Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Smalltalk

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Control flow jumping forward after the end of the outermost loop
| negativeValue |
negativeValue := [ :matrix || ctx |
    ctx := thisContext sender.
    matrix do: [ :row |
        row do: [ :value |
            (value < 0) ifTrue: [ ctx resumeWith: value ].
        ]
    ]
] value: m. "ex. m := #((1 2 -1 3))"
Transcript show: negativeValue; cr.

Normally, you would use non-local return inside a method containing just the outer loop.

thisContext allows access and manipulation of the call stack. It can be used to implement continuations, which is what the example does.
Outer_loop:
for A in M'Range (1) loop
   Inner_Loop:
   for B in M'Range (2) loop
      if M (A, B) < 0 then
         Put_Line (M (A, B)'Image);
         exit Outer_Loop;
      end if;
   end loop Inner_Loop;
end loop Outer_Loop;

New implementation...
< >
programming-idioms.org