--  Pipelines over arrays (T25b): reductions, filters, quantifiers and collections, each one
--  fused loop with generated invariants; reductions in contracts mean ghost folds.
package Stats is
   subtype Score is Integer range 0 .. 100;
   type Scores is array (Positive range <>) of Score;

   --  the sum, and the sum of those that pass
   function Total (A : Scores) return Integer is (A'Reduce ("+", 0))
   with Pre => A'Length <= 1000;

   function Passing_Total (A : Scores; Mark : Score) return Integer is
     ([for X of A when X >= Mark => X]'Reduce ("+", 0))
   with Pre => A'Length <= 1000;

   --  how many pass: each counts one
   function Passing (A : Scores; Mark : Score) return Natural is
     ([for X of A when X >= Mark => 1]'Reduce ("+", 0))
   with Pre => A'Length <= 1000;

   --  a range's values, mapped (the range's bounds bound its values)
   subtype Count is Natural range 0 .. 100;
   function Sum_Of_Squares (N : Count) return Natural is
     ([for I in 1 .. N => I * I]'Reduce ("+", 0));

   --  the largest, by a function reducer
   function Best (A : Scores) return Score is (A'Reduce (Score'Max, 0));

   --  quantifiers, with and without a filter
   function All_Valid (A : Scores) return Boolean is (for all X of A => X <= 100);
   function Any_Perfect (A : Scores) return Boolean is (for some X of A => X = 100);

   --  the scores that pass, collected into an array as long as their number
   function Above (A : Scores; Mark : Score) return Scores is
     ([for X of A when X > Mark => X])
   with Pre => A'Length <= 1000;

   --  each score curved, collected; nothing filtered, so as long as the source
   function Curved (A : Scores) return Scores is ([for X of A => (X + 100) / 2])
   with Pre => A'First = 1 and A'Length <= 1000,
        Post => Curved'Result'Length = A'Length;

   --  a loop the programmer writes, proved against the reduction it computes
   function Running_Total (A : Scores) return Integer
   with Pre => A'Length <= 1000,
        Post => Running_Total'Result = A'Reduce ("+", 0);
end Stats;
