如何在Ada中创建一个通用包?

时间:2013-12-18 16:32:40

标签: packages ada

我有一个Ada程序来计算从文件中取出的200个值的平均值和标准差,它们都正常工作。这些包是浮点类型,如何将它们变成泛型类型?

平均套餐广告文件是:

with Text_IO;
package avg is
  type int_array is Array (1..200) of integer;
  function avrage (ParArray: int_array) return float;
end avg;

并且平均包裹体是:

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;

我通过“with”和“use”在我的主程序中调用此包。请告诉我该怎么做

1 个答案:

答案 0 :(得分:1)

您没有说明您希望您的包在中是通用的

我假设您希望输入为Input_Values索引的某种类型Input_Value的数组(下面为Input_Index),并且您希望输出为某些浮点数点类型Result_Value。您需要一个函数To_Result_Value才能将Input_Value转换为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;

......实施:

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;

......还有一个小小的演示:

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;