Routines: Swap Problem Example with ADA Matrices Spring, 2000

 previous  next 
The purpose is to provide another example of copy in copy out parameter passing as well as expose the student to some more Ada code.
 
With Matrix_stuff; Use Matrix_stuff;
PROCEDURE Swap(x,y: IN OUT matrix) is
  BEGIN
x := x + y;
y := x - y;
x := x - y;
  END

BEGIN -- Main
   a:=(1..3 => ( 1..3 => 1));
   Swap (a,a);
END;



PACKAGE  Matrix_stuff  IS
TYPE index is RANGE 1..20;
TYPE matrix is ARRAY(index RANGE <>,
                     index RANGE <>) of INTEGER;
FUNCTION "+" (x,y : IN matrix) RETURN matrix;
FUNCTION "" (x,y : IN matrix) RETURN matrix;
END  Matrix_stuff;

PACKAGE  BODY  Matrix_stuff  IS
   FUNCTION "+" (x,y : IN matrix)  RETURN matrix  IS

L1 : x’FIRST(1);
U1 : x’LAST(1);
L2 : x’FIRST(2);
U2 : x’LAST(2);
z : matrix(L1..U1, L2..U2);
   BEGIN
 IF L1 /= y’FIRST(1) or U1 /= y’LAST(1) or
         L2 /= y’FIRST(2)or U2 /= y’LAST(2)
   THEN Raise CONSTRAINT_ERROR;
 END IF
 FOR  i  IN  L1..U1  LOOP
FOR j IN  L2..U2  LOOP
    z(i,j) := x(i, j) + y(i, j);
END LOOP;
 END LOOP;
 return (z);
END;
FUNCTION ”-" (x,y : IN matrix) RETURN matrix IS
L1 : x’FIRST(1);
U1 : x’LAST(1);
L2 : x’FIRST(2);
U2 : x’LAST(2);
z : matrix(L1..U1, L2..U2);
   BEGIN
 IF L1 /= y’FIRST(1) or U1 /= y’LAST(1) or
         L2 /= y’FIRST(2)or U2 /= y’LAST(2)
   THEN Raise CONSTRAINT_ERROR;
 END IF
 FOR  i  IN  L1..U1  LOOP
FOR j IN  L2..U2  LOOP
    z(i,j) := x(i, j) - y(i, j);
END LOOP;
 END LOOP;
 return (z);
END;
End Matrix_stuff;
       

 previous   next