Reputation: 323
I have an Ada program to calculate the average and standard deviation of 200 values taken from a file, and they are both working correctly. these packages are in float type, How to turn them into generic type?
The average package ads file is:
with Text_IO;
package avg is
type int_array is Array (1..200) of integer;
function avrage (ParArray: int_array) return float;
end avg;
and the average package body is:
with Text_IO;
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO;
package body avg is
function avrage (ParArray: int_array) return float is
result: float :=0.0;
final:float :=0.0;
myarray: int_array:=ParArray;
begin
for v in myarray'Range loop
result:= result + float(myarray(v));
end loop;
final:=result/200.0;
return final;
end avrage;
end avg;
I call this package in my main program by "with" and "use". please tell me what to do
Upvotes: 0
Views: 425
Reputation: 25491
You don’t say what you want your package to be generic in.
I’m assuming that you want the input to be an array (Input_Values
below) of some type Input_Value
indexed by Input_Index
, and you want the output to be of some floating-point type Result_Value
. You’ll need a function To_Result_Value
to convert Input_Value
to Result_Value
.
generic
type Input_Value is private;
type Input_Index is (<>);
type Input_Values is array (Input_Index range <>) of Input_Value;
type Result_Value is digits <>;
with function To_Result_Value (X : Input_Value) return Result_Value;
package Statistics is
function Mean (Input : Input_Values) return Result_Value;
end Statistics;
... with implementation:
package body Statistics is
function Mean (Input : Input_Values) return Result_Value is
Sum : Result_Value := 0.0;
begin
for I of Input loop
Sum := Sum + To_Result_Value (I);
end loop;
return Sum / Result_Value (Input’Length);
end Mean;
end Statistics;
... and a little demo:
with Ada.Text_IO;
with Statistics;
procedure Demo is
type Arr is array (Integer range <>) of Integer;
function To_Float (X : Integer) return Float is
begin
return Float (X);
end To_Float;
package Avg is new Statistics (Input_Value => Integer,
Input_Index => Integer,
Input_Values => Arr,
Result_Value => Float,
To_Result_Value => To_Float);
A : Arr := (1, 2, 3, 4, 5);
M : Float;
begin
M := Avg.Mean (A);
Ada.Text_IO.Put_Line ("mean is " & Float'Image (M));
end Demo;
Upvotes: 1