--  Matrices whose bounds each value has (unconstrained two-dimensional arrays): the trace,
--  the transpose, the product, and the totals of each row and each column.
package Matrices
  with SPARK_Mode
is
   subtype Small is Integer range -100 .. 100;
   type Matrix is array (Positive range <>, Positive range <>) of Small;
   type Wide is array (Positive range <>, Positive range <>) of Integer;
   type Totals is array (Positive range <>) of Integer;

   subtype Extent is Natural range 0 .. 10;

   function Square (M : Matrix) return Boolean is (M'Length (1) = M'Length (2));

   function Trace (M : Matrix) return Integer
     with Pre => Square (M) and M'Length (1) in Extent,
          Post => Trace'Result in -1_000 .. 1_000;

   function Transpose (M : Matrix) return Matrix
     with Pre => M'Length (1) in Extent and M'Length (2) in Extent,
          Post => Transpose'Result'First (1) = M'First (2)
            and Transpose'Result'Last (1) = M'Last (2)
            and Transpose'Result'First (2) = M'First (1)
            and Transpose'Result'Last (2) = M'Last (1)
            and (for all I in M'Range (1) =>
                   (for all J in M'Range (2) => Transpose'Result (J, I) = M (I, J)));

   function Product (A, B : Matrix) return Wide
     with Pre => A'Length (2) = B'Length (1)
            and A'Length (1) in Extent and A'Length (2) in Extent and B'Length (2) in Extent,
          Post => Product'Result'First (1) = A'First (1)
            and Product'Result'Last (1) = A'Last (1)
            and Product'Result'First (2) = B'First (2)
            and Product'Result'Last (2) = B'Last (2);

   function Row_Totals (M : Matrix) return Totals
     with Pre => M'Length (2) in Extent,
          Post => Row_Totals'Result'First = M'First (1) and Row_Totals'Result'Last = M'Last (1);

   function Column_Totals (M : Matrix) return Totals
     with Pre => M'Length (1) in Extent,
          Post => Column_Totals'Result'First = M'First (2) and Column_Totals'Result'Last = M'Last (2);

   function Identity (N : Extent) return Matrix
     with Post => Identity'Result'First (1) = 1 and Identity'Result'Last (1) = N
       and Identity'Result'First (2) = 1 and Identity'Result'Last (2) = N
       and (for all I in 1 .. N => (for all J in 1 .. N => Identity'Result (I, J) in 0 .. 1));

   function Count_Above (M : Matrix; Limit : Small) return Natural
     with Pre => M'Length (1) in Extent and M'Length (2) in Extent;
end Matrices;
