Logo

Programming-Idioms

  • Python
  • Perl

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

sub search {
   my ($x, $m) = @_;
   while ( ($k1,$v1) = each @$m ) {
      while ( ($k2, $v2) = each @$v1 ) {
           return $k1, $k2 if $v2 == $x;
      }
   }
}
def search(x, m):
    for i, M in enumerate(m):
        for j, N in enumerate(M):
            if N == x: return (i, j)

This will return a tuple.
def search(m, x):
    for idx, item in enumerate(m):
        if x in item:
            return idx, item.index(x)
type Matrix is array (Positive range <>, Positive range <>) of Integer;

function Search (M : Matrix; X : Integer; I, J : out Integer) return Boolean is
begin
   for K in M'Range (1) loop
      for L in M'Range (2) loop
         if M (K, L) = X then
            I := K;
            J := L;
            return True;
         end if;    
      end loop;
   end loop;

   return False;
end Search;

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