Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Obj-c

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.

@import Foundation;
NSIndexPath *search(NSArray *m,id x) {
  NSUInteger j,i;
  for (i=0;i<m.count;i++) {
    if ((j=[m[i] indexOfObject:x])!=NSNotFound)
      return [NSIndexPath indexPathWithIndexes:&i length:2];
  }
  return nil;
}

In practice, it would not be implemented as a function, but as a new method of NSArray. Note we read the indices directly from the stack; with really weird architectures might be safer to use ij[2] instead
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