Logo

Programming-Idioms

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

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
find_negative_in([]) -> undefined;
find_negative_in([Row|Rows]) -> find_negative_in(Row, Rows).

find_negative_in([], Rows) -> find_negative_in(Rows);
find_negative_in([Pos|Values], Rows) when Pos >= 0 ->
	find_negative_in(Values, Rows);
find_negative_in([Neg|_], _) -> Neg.

Assuming the matrix is implemented as a list of lists.
We just use a recursive function that instead of printing the value, just returns it.
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